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)
Related
I am using a postman to automate apis.
Now I am using following request , lets say :-
{
"customerId": "{{currentClientId}}"
}
Where clientid is a dynamic variable whose value is substituted dynamically as 1 , 2, 3,4 so on..
I call this request multiple times using setNextRequest call in this eg lets say 10.This is being done using a counter variable. I am initialising the counter in my previous request to 0 and using for loop with value as counter as 10 calling the request 10 times.There is no response in body just successful http code 204.
I want to store all these clientids coming in request into an environment Client array variable so I wrote a following pre-request script:-
counter = pm.environment.get("counter");
ClientArray = pm.environment.get("ClientArray");
ClientArray.push(pm.environment.get("currentClientId"));
pm.environment.set("ClientArray",ClientArray);
In Test Script, wrote following code :-
counter = pm.environment.get("counter");
if(counter<=10) {
console.log("hi");
postman.setNextRequest("Request");
counter++;
pm.environment.set("counter",counter);
console.log("Counter",counter);
}
The above scipts is throwing
TypeError | ClientArray.push is not a function.
Could someone please advice how to achieve this.
When you retrieve a value from an environment variable like you're doing:
ClientArray = pm.environment.get("ClientArray");
You're not getting an array, you're getting a string which is why you're getting that error. You need to treat the variable like a string, append the currentClientId much like you do for the counter. Something like:
var currentClientIds = pm.environment.get("ClientArray");
currentClientIds = currentClientIds + "," + currentClientId
When you're done appending i.e. out of your loop simply take the string and convert it to an array:
var currentClientIds = pm.environment.get("ClientArray");
var idsArr = curentClientIds.split(',');
I have a list of names in a google sheet. I'm trying to create a function in google apps scripts that outputs the next name in the list to a different cell in the spreadsheet. Once I've returned each name, I want to go back to the beginning.
I've tried to use a for loop as well, but then the script just loops through every item, and I end up with the just the last item being returned.
function returnNextName() {
var nameList =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My
Homeroom").getRange(2, 1, 22).getValues();
var outputCell =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My
Homeroom").getRange(1, 4);
var i = 0;
i = i + 1;
i = i%nameList.length;
var nextName = outputCell.setValue(nameList[i]);
}
My goal is that every time I run the function, I will get the next name in the list. However, I only ever get the first name.
Every time you call the script you redefine
var i = 0;
i = i + 1;
i = i%nameList.length;
So your element nameList[i] will be always the same.
To avoid this, you need to use PropertiesService, as suggested by TheMaster.
ScriptProperties allows you to store the last index in the script properties and retrieve and modify it every time you use the script.
Sample:
if(PropertiesService.getScriptProperties().getKeys().length==0){ // first time you run the script
PropertiesService.getScriptProperties().setProperty('i', 0);
}
var i = Number(PropertiesService.getScriptProperties().getProperty('i'))%nameList.length;
outputCell.setValue(nameList[i][0]);
i++;
PropertiesService.getScriptProperties().setProperty('i', i);
I'm new to Swift. I can read data (many rows and columns of names and mailing addresses) from csv file format. I have several of these files, so I created a function just to read the files and extract the data into a multidimensional array(s) - names, addresses, city, state, country. I read each of the lines from the file and try to append it to multidimensional array but I get errors - either index out of range or file type mismatch. What's the best way to enable this. See code below.
func getMailing(fileName: String) -> ([[String]])? {
let totalList = 243
var tempList: [String] = []
var arrayList = [[String]]()
guard let path = Bundle.main.url(forResource: fileName, withExtension: "csv") else {
print("File Error")
arrayList = [[""]]
return (arrayList)
}
do {
// get mailing data from file
let content = try String(contentsOf:path, encoding: String.Encoding.utf8)
// separate each line entry
tempList = content.components(separatedBy: "\r\n")
for index in 0...totalList - 1 {
// get each line from list and post into an array
let singleLine = tempList[index].components(separatedBy: ",").dropFirst().prefix(5)
// store each line data into into a multidimensional array for easy retrieval
arrayList[index].append(singleLine)
}
}
return (arrayList)
} catch {
print("File Error")
arrayList = [[""]]
return (arrayList)
}
}
Based on the code you've shown, it looks like you're trying to change the values of two different empty arrays 243 times. You have a loop setup to iterate based on your totalList property, but where you got that value, I have no idea. It would be wise to determine that value programmatically if you can.
You're setting both tempList and arrayList as empty arrays:
var tempList: [String] = []
var arrayList = [[String]]()
But then you're going through a loop and trying to change the value of an entry that doesn't even exist, hence your index out of range error. You need to first add something to both these arrays, because right now they are empty. It's probably crashing the first time through the loop when you try to set singleLine to tempList[index].components(separatedBy: ",").dropFirst().prefix(5), because you're saying tempList[0].components(separatedBy: ",").dropFirst().prefix(5), while there isn't an entry for tempList at index 0 because it's still empty! If you're going to loop through an array, it's always wise to do it based on the count of the array, or at least a quick fix when you need to use an index from two different arrays:
// Get the maximum times you can iterate based on the lowest count from each array
let maxLoop = min(tempList.count - 1, arrayList.count - 1)
for index in 0...maxLoop {
// get each line from list and post into an array
let singleLine = tempList[index].components(separatedBy: ",").dropFirst().prefix(5)
// store each line data into into a multidimensional array for easy retrieval
arrayList[index].append(singleLine)
}
Now that little chunk of code above won't even go through the loop once, because both arrays are still empty. You need to somewhere take your mailing data and parse it so that you can populate tempList and arrayList
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...)
I have a map which has as value an array of maps.
Example:
thisMap["coins"][0] = aMap["random":"something"]
thisMap["notes"][1] = aMap["not-random":"something else"]
thisMap["coins"][2] = aMap["not-random":"something else"]
I can't figure it out how to do this as go seems to allow setting data only at one level when you deal with maps [name][value] = value.
So far I have this code which fails
package main
func main() {
something := []string{"coins", "notes", "gold?", "coins", "notes"}
thisMap := make(map[string][]map[string]int)
for k, v := range something {
aMap := map[string]string{
"random": "something",
}
thisMap[v] = [k]aMap
}
}
Edit: The slice values ("coins", "notes" etc ) can repeat so this is the reason why I need use an index [] .
Working example (click to play):
something := []string{"coins", "notes", "gold?"}
thisMap := make(map[string][]map[string]int)
for _, v := range something {
aMap := map[string]int{
"random": 12,
}
thisMap[v] = append(thisMap[v], aMap)
}
When iterating over the newly created thisMap, you need to make room for the new value aMap. The builtin function append does that for you when using slices. It makes room and appends the value to the slice.
If you're using more complex data types that can't be initialized as easily as slices, you first have to check if the key is already in the map and, if it is not, initialize your data type. Checking for map elements is documented here. Example with maps (click to play):
thisMap := make(map[string]map[string]int)
for _, v := range something {
if _, ok := thisMap[v]; !ok {
thisMap[v] = make(map[string]int)
}
thisMap[v]["random"] = 12
}