Go: Append byte slices in a loop [duplicate] - arrays

This question already has answers here:
How can I use Go append with two []byte slices or arrays?
(2 answers)
Closed 7 years ago.
I'm new to Go, so I apologise if this has already been answered, I'm trying to append a byte slice in Go and I am not having any luck finding a solution. I need to split off the first line of the file, which I've done; And write the rest into a byte slice to be parsed after the fact. So far the code looks like this:
// Here we extract the first line to name our title and category
var title, category string
var content []byte
in, err := os.Open(file)
utils.CheckErr(err, "could not open file: "+file)
defer in.Close()
// open file
scanner := bufio.NewScanner(in)
lineCount := 1
for scanner.Scan() {
if lineCount == 1 {
// assign title and category
splitString := strings.Split(scanner.Text(), "::")
title = splitString[0]
category = splitString[1]
fmt.Println("title: " + title + "category" + category) // usage to prevent compiler whine
} else {
// push the rest into an array to be parsed as jade
line := scanner.Bytes()
content = append(content, line) // The question is what goes here?
}
lineCount++
}
I've tried using append but that only gives me the error that
cannot use line (type []byte) as type byte in append

I believe you're simply looking for; content = append(content, line...)

See https://golang.org/ref/spec#Appending_and_copying_slices
There is probably a duplicate but until I find it...
Your problem is solved by adding "..." to the end of line so it looks like:
content = append(content, line...)

Related

Why this code is generating array index out of bound?

I am stuck for past 5 - 6 hours in figuring this out that why this code is generating array index out of bound error on run time. I am unable to find out the reason. Can you please tell what modifications are required to correct this code?
spotsArr := make(map[int][]map[int64][]int)
for ind, availableSpot := range availableSpots {
spotsArr[availableSpot.Uid][ind] = make(map[int64][]int)
spotsArr[availableSpot.Uid][ind][availableSpot.Date] = []int{availableSpot.SpotSlug}
}
fmt.Println(spotsArr)
Edit 1: View the full code here https://play.golang.org/p/Smm0BFgtNp
Edit 2: Actually what I need to do is to get output in format something like:
{ uid: { date: {spot_slug, spot_slug} } }
{ 86: { 1536710400: {1000, 1200, 900},
{ 1536105600: {900} } }
The error is, as the error message suggests, because you tried to assign element on the index greater than the slice length. For the sake of getting the error away, you can just initialize the slice to the length, at least, as much as the index you wanted to use :
....
spotsArr[availableSpot.Uid] = make([]map[int64][]int, ind+1, ind+1)
spotsArr[availableSpot.Uid][ind] = make(map[int64][]int)
....
But as you clarified further about the desired output, it seems that you don't need slice in the first place. You need map of Uid where each key has value of map of Date :
spotsArr := make(map[int]map[int64][]int)
for _, availableSpot := range availableSpots {
if _, ok := spotsArr[availableSpot.Uid]; !ok {
spotsArr[availableSpot.Uid] = make(map[int64][]int)
}
spotsArr[availableSpot.Uid][availableSpot.Date] = append(spotsArr[availableSpot.Uid][availableSpot.Date],availableSpot.SpotSlug)
}
fmt.Println(spotsArr)
playground
Given the last two data have the same date, the output is as follows :
map[86:map[1534896000:[900] 1535500800:[900] 1536105600:[900] 1537315200:[900 900]]]
spotsArr is a map of int to an array of maps - map[int][]...
spotsArr := make(map[int][]map[int64][]int)
On this line, you try to assign to an index of that array which has no members yet:
spotsArr[availableSpot.Uid][ind] = make(map[int64][]int)
You're saying set this spot availableSpot.Uid to something (fine) but then set the index ind in an array which doesn't have members to something else (not fine). To fix this I'd recommend trying to do less on each line so that it's much clearer where and what the problem is. You could do this to fix the grammar error:
spotsArr[availableSpot.Uid] = []map[int64][]int{make(map[int64][]int)}
But I can't think why you want to set an index on the map to the index of the Uids you're traversing (your code doing [Ind]). I'd try to make this less complex and confusing if you can and spread it out on several lines to make the intent clear.
PS Give people a code sample which runs (i.e. include all the structs used), it makes it easier to help.
PPS Thanks for code sample, that makes it clearer.

Appending slice not working as expected

New to golang. Im trying to store all the waypoints sent over from our app side, but with a batch size of 100, here's my code
json.NewDecoder(r.Body).Decode(payload)
// seperate waypoints into groups
limit := 100
seperated := [][]*waypoint.Waypoint{}
// payload is from api call, basically plain json data
for i, wp := range payload.Batch {
if i%limit == 0 {
seperated = append(seperated, []*waypoint.Waypoint{})
}
last := seperated[len(seperated)-1]
last = append(last, wp)
}
Not sure what went long but seems i cant what i expected..
You're making a copy of your slice when you assign it to last, so when you append that isn't reflected in the outer seperated slice.
Assign it directly like so:
last := len(seperated)-1
seperated[last] = append(seperated[last], wp)

Value isnt saved after inputstring on TDBWPRichText to linked MemoField

i have a TDBWPRichText linked to a MemoField on my Database.
when i press a Button i want the formated text to prepend some text.
the visual component shows the the prepended string, but when i Post, the Value of the memo doesnt change.
MyTable.Edit;
DBRichedit1.SelLength := 0;
DBRichedit1.CPPosition := 0;
DBRichedit1.Inserting := True;
DBRichedit.InputString('Test:' + #13);
//it shows the value on the component here
MyTable.Post;
in the MyTableBeforePost the Field has the old value though apparently
Field.Value <> Field.OldValue
If i enter text manually it works just fine
i also tried to save it manually (where the comment is) but the String is the old value
DBRichedit.SaveToString(MyTable.FieldByName('MyMemo').AsString,False);
Is there anyway i can get the prepended String into my Table?
This was a lot trickier than I was expecting it to be, even though I recalled that working with RichText in Delphi code can be a bit of a pain.
Anyway, the following works for me, to add an Rtf header stored in a disk file; see if it does for you. It isn't pretty and I can't help thinking that it's inordinately
long-winded.
procedure TForm1.InsertHeader;
// Prepend an RTF header to an existing RTF DB field
var
TL : TStringList;
ExistingText : String;
RE : TRichEdit;
MS : TMemoryStream;
begin
MS := TMemoryStream.Create;
TL := TStringList.Create;
// The reason for using a temporary RichEdit is to enlist its assistance
// in manipulating the rich text
RE := TRichEdit.Create(Nil);
RE.Parent := Self;
try
ExistingText := AdoQuery1.FieldByName('Memo').AsString;
RE.Clear;
// The reason for using the richedit's SelText in the following is that my
// initial naive attempt to assign to its Lines.Text provoked a "Line Insertion Error"
RE.SelStart := 0;
RE.SelText := ExistingText + #13#10;
TL.LoadFromFile('\d7\demos\richedit\header.rtf');
RE.SelStart := 0;
RE.SelText := RE.SelText + TL.Text;
RE.Lines.SaveToStream(MS);
MS.Position := 0;
AdoQuery1.Edit;
TMemoField(AdoQuery1.FieldByName('Memo')).LoadFromStream(MS);
AdoQuery1.Post;
finally
TL.Free;
RE.Free;
MS.Free;
end;
end;
Btw, there is an answer to how to insert RTF into pre-existing RTF in a TRichEdit here: http://delphidabbler.com/tips/57
After some hours i resorted to the dev of WPtools and he promptly provided me with the answer which is incredible simple:
you have to call
RichEdit.Changing
before interacting with it within the code

Reading a list from a file in python 3

While trying to make a simple register/signup client only application for a personal project. I'm trying to load a list of users from a file, and compare them to a possible username. If the username already exists, the program will give them an error.
Here is a condensed clone of the code:
u1 = str(input("Input username: "))
t = open("userlistfile","r")
userlist = t.readline()
y = 0
for x in range(0, len(userlist)-1):
if userlist[y] == u1:
print("\n !Error: That username (",u1,") is already taken!")
y += 1
The user list is stored in a file so that it can opened, appended, and saved again, without being stored in the program. My current issue is that the userlist is saved as a string rather than an array. Is there a better way to do this? Thank you.
EDIT: Thanks to user lorenzo for a solution. My Friends are telling me to post a quick (really simple) copy of a for you guys who can't figure it out.
New code:
u1 = str(input("Input username: "))
t = open("userlistfile","r")
userlist = t.read() #Readline() changed to Read()
userlist = userlist.split('--') #This line is added
y = 0
for x in range(0, len(userlist)-1):
if userlist[y] == u1:
print("\n !Error: That username (",u1,") is already taken!")
y += 1
Example text file contents:
smith123--user1234--stacky
This line will seperate the string at the ('--') seperators and append each split part into an array:
userlist = userlist.split('--')
#Is used so that this (in the text file)
Smith123--user1234--stacky
#Becomes (in the program)
userlist = ['Smith123','user1234','stacky']
Sorry for the long post... Found it very interesting. Thanks again to Lorenzo :D.
userlist = t.readline()
reads one line from the file as a string. Iterating, then, gets characters in the string rather than words.
You should be able to get a list of strings (words) from a string with the split() method of strings or the more general re.split() function.

Non-cell array with uigetfile in Matlab

My code has 2 parts. First part is an automatic file opening programmed like this :
fichierref = 'H:\MATLAB\Archive_08112012';
files = dir(fullfile(fichierref, '*.txt'));
numberOfFiles = numel(files);
delimiterIn = ' ';
headerlinesIn = 11;
for d = 1:numberOfFiles
filenames(d) = cellstr(files(d).name);
end
for i=1:numberOfFiles
data = importdata(fullfile(fichierref,filenames{i}),delimiterIn,headerlinesIn);
end
Later on, I want the user to select his files for analysis. There's a problem with this though. I typed the lines as follow :
reference = warndlg('Choose the files from which you want to know the magnetic field');
uiwait(reference);
filenames = uigetfile('./*.txt','MultiSelect', 'on');
numberOfFiles = numel(filenames);
delimiterIn = ' ';
headerlinesIn = 11;
It's giving me the following error, after I press OK on the prompt:
Cell contents reference from a non-cell array object.
Error in FreqVSChampB_no_spec (line 149)
data=importdata(filenames{1},delimiterIn,headerlinesIn);
I didn't get the chance to select any text document. Anyone has an idea why it's doing that?
uigetfile is a bit of an annoying when used with `MultiSelect': when you select multiple files the output is returned as a cell array (of strings). However, when only one file is selected the output is of type string (not a cell array with a single cell, as one would have expected).
So, in order to fix this:
filenames = uigetfile('./*.txt','MultiSelect', 'on');
if ~iscell(filenames) && ischar( a )
filenames = {filenames}; % force it to be a cell array of strings
end
% continue your code here treating filenames as cell array of strings.
EDIT:
As pointed out by #Sam one MUST verify that the user did not press 'cancel' on the UI (by checking that filenames is a string).

Resources