I'm trying to make a function that reads a collection of data from JSON file, but I keep receiving this error
panic: runtime error: index out of range
and it's not importing all the data from json file,
I think there's something wrong in my for loop.
// read our opened xmlFile as a byte array.
byteValue, _ := ioutil.ReadAll(jsonFile)
// initialize Int array
var interns Int
// initialize Com array
var companies Com
// unmarshal byteArray
json.Unmarshal(byteValue, &interns)
json.Unmarshal(byteValue, &companies)
// iterate through every student within our students array and
// print out the student ID, first & last name
for i := 0; i < len(interns.Int); i++ {
fmt.Println("Student first name: " + interns.Int[i].Name.FirstName)
fmt.Println("Student last name: " + interns.Int[i].Name.LastName)
fmt.Println("Company name: " + companies.Com[i].CompanyName)
fmt.Println("Company email address: " + companies.Com[i].CompanyEmail + "\n")
}
Because you are using len of Int array to iterate Com array while len of Com array is different so the program will panic when iterate to an index that Com array is not available
//Program panics if [i] is not valid
fmt.Println("Company name: " + companies.Com[i].CompanyName)
fmt.Println("Company email address: " + companies.Com[i].CompanyEmail + "\n")
Split the loop into two to iterate and it will works
// iterate Int array
for i := 0; i < len(interns.Int); i++ {
fmt.Println("Student first name: " + interns.Int[i].Name.FirstName)
fmt.Println("Student last name: " + interns.Int[i].Name.LastName)
}
// iterate Com array
for i := 0; i < len(companies.Com); i++ {
fmt.Println("Company name: " + companies.Com[i].CompanyName)
fmt.Println("Company email address: " + companies.Com[i].CompanyEmail + "\n")
}
Related
As a JS dev jumping right into Go, I've hit a deadend trying to print multiple descriptions if the length of commits is more than one. I don't have much time left to complete this and I've been searching for longer than I wish. Any idea on how I could either restructure this or get this to work?
case github.PushPayload:
push := payload.(github.PushPayload)
repo := push.Repository.Name
owner := push.Repository.Owner.Login
ownerUrl := push.Repository.Owner.HTMLURL
ownerAvatar := push.Repository.Owner.AvatarURL
ref := push.Ref
refTrim := strings.Replace(ref, "/.*/", "", -1)
commits := push.Commits
for _, commit := range commits {
message := commit.Message
url := commit.URL
id := commit.ID
idShort := id[0:6]
committer := commit.Committer.Username
description := "[`" + idShort + "`](" + url + ") " + message + " - " + committer
}
if len(commits) == 1 {
discord.ChannelMessageSendEmbed(channelID, &discordgo.MessageEmbed{
Color: 0x00B1FF,
Description: description,
Title: "[" + repo + ":" + refTrim + "] 1 new commit! 🔧",
Author: &discordgo.MessageEmbedAuthor{
Name: owner,
URL: ownerUrl,
IconURL: ownerAvatar,
},
})
} else {
discord.ChannelMessageSendEmbed(channelID, &discordgo.MessageEmbed{
Color: 0x00B1FF,
Description: description,
Title: "[" + repo + ":" + refTrim + "] " + string(len(commits)) + " new commits! ⚒️",
Author: &discordgo.MessageEmbedAuthor{
Name: owner,
URL: ownerUrl,
IconURL: ownerAvatar,
},
})
}
PS: Ignore string(len(commits)) I know that's incorrect, I'm stuck trying to figure this out first and foremost. Also ignore: refTrim := strings.Replace(ref, "/.*/", "", -1), which isn't correct either.
you have to declare description variable before the loop and then add commit descriptions to it as below inside the loop.
Note: I emitted other code blocks here.
description := ""
for _, commit := range commits {
description = description + "commit description here"
}
description += "commit description here" also can be used inside the loop. But I have added above to more understanding.
I want to compare my list of stocks price with my set Stoploss which is stored and once the condition trigger alert by email. Below is my code
function emailAlert()
{
var stock1nameRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Watchlist").getRange("A5");
var stock1name = stock1nameRange.getValues();
var stock1cmpRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Watchlist").getRange("B5");
var stock1cmp = stock1cmpRange.getValues();
var stock1s1Range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Watchlist").getRange("AK5");
var s1 = stock1s1Range.getValues();
var stock1s2Range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Watchlist").getRange("AL5");
var s2 = stock1s2Range.getValues();
var ui = SpreadsheetApp.getUi();
if(stock1cmp<s1)
{
if(stock1cmp<s2)
{
ui.alert( stock1name + stock1cmp + 'is less than' +s2 );
var message = stock1name + stock1cmp + 'is less than' +s2 ;
MailApp.sendEmail("#gmail.com", "Stock Watchlist alert", message)
return s2
}
else
{
ui.alert( stock1name + stock1cmp + 'is less than' +s1 );
var message = stock1name + stock1cmp + 'is less than' +s1 ;
MailApp.sendEmail("#gmail.com", "Stock Watchlist alert", message )
return s1
}
}
}
This is for single stock. How can I make it more generic and compile all the stock list which pass the condition into single mail. Thanks.
Sen
In order to be able to select all the values you will be needing a for loop.
Snippet
function emailAlert() {
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName("Watchlist");
var stockName = sheet.getRange("A5:FINAL_RANGE").getValues();
var stockCmp = sheet.getRange("B5:FINAL_RANGE").getValues();
var s1 = sheet.getRange("AK5:FINAL_RANGE").getValues();
var s2 = sheet.getRange("AL5:FINAL_RANGE").getValues();
for (var i = 0; i < stockName.length; i++) {
if (stockCmp[i][0] < s1[i][0]) {
if (stockCmp[i][0] < s2[i][0]) {
ui.alert(stockName[i][0] + stockCmp[i][0] + ' is less than ' + s2[i][0]);
var message = stockName[i][0] + stockCmp[i][0] + ' is less than ' + s2[i][0];
MailApp.sendEmail("#gmail.com", "Stock Watchlist Alert", message);
return s2[i][0];
} else {
ui.alert(stockName[i][0] + stockCmp[i][0] + ' is less than ' + s1[i][0]);
var message = stockName[i][0] + stockCmp[i][0] + ' is less than ' + s1[i][0];
MailApp.sendEmail("#gmail.com", "Stock Watchlist Alert", message);
return s1[i][0];
}
}
}
}
Explanation
The above code loops through all the values from your columns by using a for loop and then based on the conditions you set, is sending the email and alerting the user. The range is retrieved by using the getRange() method with the a1Notation parameter. The a1Notation parameter here is represented by the start and the end of the range in which you have the values you need for the script.
Note
The above script is built considering the fact that the stockName, stockCmp, s1, s2 are all associated, meaning that they all have the same number of values stored in them.
Reference
Apps Script Range Class - getValues();
Apps Script Sheet Class - getRange(a1Notation);
JavaScript For Loop.
I m trying to take an input from the user through my console in golang by using fmt.Scanln(). It is working fine under normal circumstances. However, whenever I take input in a loop, the inputs are correct in the first iteration but during the next iterations of a loop, an extra smiley is added in the front of the received string. I don't know what the problem is. Will be very thankful if anyone proposes some solution.
func (a *Block) fillBlock() {
fmt.Println("Block Details:")
fmt.Print("Enter Block Name: ")
fmt.Scanln(&a.Data)
for i := 0; i < Students; i++ {
fmt.Print(i, "Enter Student Roll# ")
fmt.Scanln(&a.Grades[i].Rollno)
fmt.Print(i, "Enter Student Grade# ")
fmt.Scanln(&a.Grades[i].Grade)
}
fmt.Println("\nInput Data:")
fmt.Println("Data: ",a.Data)
// Iterating over each student
for i := 0; i < Students && (a.Grades[i].Rollno != "" && a.Grades[i].Grade != ""); i++ {
fmt.Println("Rollno: " + string(i) + a.Grades[i].Rollno)
fmt.Println("Grade: " + string(i) + a.Grades[i].Grade)
}
}
This is wrong:
fmt.Println("Rollno: " + string(i) + a.Grades[i].Rollno)
Instead, use
fmt.Println("Rollno: " + strconv.Itoa(i) + a.Grades[i].Rollno)
Or, better:
fmt.Printf("Rollno: %d %s\n",i a.Grades[i].Rollno)
Working on chapel currently and trying to iterate through an array hi of type: eltType called elements and it has elements in it.
I am trying to iterate through the whole array hi and print out each element so I'm doing:
var hi : int;
hi = elements.size;
forall i in hi
{
writeln("Index: ", 0, " Element: ", elements[i]);
}
When I try that I get this error:
Cannot iterate over values of type int(64)
Not sure how to iterate through it or why this error is happening.
Any ideas or guides? I've been looking at the Chapel API.
Your code sample has a bug, since 'hi' is an integer (storing the size of the array). You might have meant 'forall i in 1..hi' for example. Either way, here is a code listing with some common patterns for such iteration.
// Declare a 1-D array storing 10, 20, 30
// Such array literals start at index 1
var elements = [10,20,30];
// Note: elements.domain is the index set of the array;
// in this case {1..3}.
writeln("loop 1");
// iterate over range, accessing elements
for i in 1..elements.size {
writeln("Index: ", i, " Element: ", elements[i]);
}
writeln("loop 2");
// as above, but in parallel (output order will differ run to run)
forall i in 1..elements.size {
writeln("Index: ", i, " Element: ", elements[i]);
}
writeln("loop 3");
// zippered iteration to iterate over array, indexes at once
for (element,i) in zip(elements,elements.domain) {
writeln("Index: ", i, " Element: ", element);
}
writeln("loop 4");
// as above, but in parallel (output order will differ run to run)
forall (element,i) in zip(elements,elements.domain) {
writeln("Index: ", i, " Element: ", element);
}
See also
http://chapel.cray.com/docs/latest/users-guide/base/forloops.html
http://chapel.cray.com/docs/latest/users-guide/base/zip.html
http://chapel.cray.com/docs/latest/primers/ranges.html
It is necessary to create a program that will on the basis of input N car number plate ( eg . " KR 635 B " ) to count the number of vehicles from individual places . At the end of the program to print the amount of vehicles coming from a particular place , and the number of vehicles whose region is not recognized . Places that recognizes :
KR - Karlovac
BJ Bjelovar ...
I need a piece of code that identifies the first part of plate lets say: " KR " , because when I use if ( input = " KR " );
then recognizes only if I enter " KR " and not the entire registration .
You can use the StartsWith method to check the beginning of a string. Example:
if (plate.StartsWith("KR")) {
...
}
If you are checking for muliple vales, you might want to get that part of the string as a separate string. You can get the first two characters:
string region = plate.Substring(0, 2);
Or the characters up to the first space:
string region = plate.Substring(0, plate.IndexOf(' '));
bool again = true;
//variable
int bje = 0;
int zgr = 0;
int spt = 0;
int vzn = 0;
int npo = 0;
//petlja za y/n
while(again)
{
// program unutar loopa
Console.WriteLine("Unesite registarsku oznaku: ");
string unos = Console.ReadLine();
if (unos == "bj")
//
bje++;
else if (unos == "zg")
//
zgr++;
else if (unos == "sp")
//
spt++;
else if (unos == "vz")
//
vzn++;
else
npo++;
Console.WriteLine("Bjelovar: " + bje);
Console.WriteLine("zagreb: " + zgr);
Console.WriteLine("split: " + spt);
Console.WriteLine("varazdin: " + vzn);
Console.WriteLine("Nepoznato: " + npo);
// za ponovan unos loop
Console.WriteLine();
Console.WriteLine("Ponovni unos? (Da/Ne)");
string YN = Console.ReadLine();
while (YN != "Y" && YN != "N" )
{
Console.WriteLine("Wrong entry. Again? (Y/N)");
YN = Console.ReadLine();
}
if (YN == "n")
{
again = false;
}
}
See i need those "if statments" changed for that word recognition and just done that is under the if statment.