Why is my Index was out of range in MVC 4? - asp.net-mvc-4

I've tried to create some list with increase number after some calculation each month for a year.
For example, in month 1 number = 1, month 2 number = 3, month 3 number = 5.
The calculation is like this number[i] = i + number[i - 1]. Which i is the month.
I want to show all the list like this
Month[1] = 1,
Month[2] = 3,
Month[3] = 5,
Month[4] = 7,
Month[5] = 9,
Month[6] = 11,
Month[7] = 13,
...
Month[12] = 23
Here's my Controller
for (i = 1; i <= 12; i++)
{
List<int> number = new List<int>();
if (i <= 12)
{
number[i] = a(i, number[i - 1]);
}
else
{
//something else
}
}
Here's my a function
public int a(int month, int number)
{
try
{
a = month + number;
}
catch (Exception ex)
{
throw ex;
}
return a;
}
But, when executed i'm getting this error
Index was out of range. Must be non-negative and less than the size of the collection.
I've change the controller into this
for (i = 0; i <= 12; i++)
{
//...
}
But have the same error. Can someone help me? Why I'm getting this error?

Try this
Fiddle demo
int[] number = new int[13];
for (int i = 1; i <= 12; i++)
{
if (i <= 12)
{
number[i] = a(i, number[i - 1]);
}
else
{
//something else
}
}
int j = 1;
List<int> item = new List<int>();
foreach (var a in number)
{
if (j <= 12)
{
item.Add(a);
}
else
{
break;
}
j++;
}
public int a(int month, int number)
{
int a = 0;
try
{
a = month + number;
}
catch (Exception ex)
{
throw ex;
}
return a;
}

Related

Does Sql batch query execution involve multiple exhange of data between server and client?

Batch query execution from what I have read from multiple sources online have been stating that it enables grouping multiple statements together and executing it at once, thereby eliminating multiple back and forth communication.
Some sources that claim this are:
https://www.tutorialspoint.com/jdbc/jdbc-batch-processing.htm#:~:text=Batch%20Processing%20allows%20you%20to,communication%20overhead%2C%20thereby%20improving%20performance.
http://tutorials.jenkov.com/jdbc/batchupdate.html
https://www.baeldung.com/jdbc-batch-processing
All of these talk about single network trip etc, however going through the source code of H2 or Sqlite, it does look like its executing one by one. Albeit with autocommit disabled.
Eg: Sqlite
final synchronized int[] executeBatch(long stmt, int count, Object[] vals, boolean autoCommit) throws SQLException {
if (count < 1) {
throw new SQLException("count (" + count + ") < 1");
}
final int params = bind_parameter_count(stmt);
int rc;
int[] changes = new int[count];
try {
for (int i = 0; i < count; i++) {
reset(stmt);
for (int j = 0; j < params; j++) {
rc = sqlbind(stmt, j, vals[(i * params) + j]);
if (rc != SQLITE_OK) {
throwex(rc);
}
}
rc = step(stmt);
if (rc != SQLITE_DONE) {
reset(stmt);
if (rc == SQLITE_ROW) {
throw new BatchUpdateException("batch entry " + i + ": query returns results", changes);
}
throwex(rc);
}
changes[i] = changes();
}
}
finally {
ensureAutoCommit(autoCommit);
}
reset(stmt);
return changes;
}
Eg: H2
public int[] executeBatch() throws SQLException {
try {
debugCodeCall("executeBatch");
if (batchParameters == null) {
// Empty batch is allowed, see JDK-4639504 and other issues
batchParameters = Utils.newSmallArrayList();
}
batchIdentities = new MergedResult();
int size = batchParameters.size();
int[] result = new int[size];
SQLException first = null;
SQLException last = null;
checkClosedForWrite();
for (int i = 0; i < size; i++) {
Value[] set = batchParameters.get(i);
ArrayList<? extends ParameterInterface> parameters =
command.getParameters();
for (int j = 0; j < set.length; j++) {
Value value = set[j];
ParameterInterface param = parameters.get(j);
param.setValue(value, false);
}
try {
result[i] = executeUpdateInternal();
// Cannot use own implementation, it returns batch identities
ResultSet rs = super.getGeneratedKeys();
batchIdentities.add(((JdbcResultSet) rs).result);
} catch (Exception re) {
SQLException e = logAndConvert(re);
if (last == null) {
first = last = e;
} else {
last.setNextException(e);
}
result[i] = Statement.EXECUTE_FAILED;
}
}
batchParameters = null;
if (first != null) {
throw new JdbcBatchUpdateException(first, result);
}
return result;
} catch (Exception e) {
throw logAndConvert(e);
}
}
From the above code I see that there are multiple calls to the database, with each having its own result set. How does batch execution actually work?

Execution gets stuck at date picking functionality of selenium webdriver

I am new to selenium automation, I have written a script to pick check in and check out dates from webpage of tripadvisor.in. I hope the code and xpaths are correct coz out of 7 or 8 executions the scrips successfully running only once. I thought abt synchronization issue and tried adding all types of waits but still the execution getting stuck as calendar. Sometimes stucking at check-in date, sometimes at check-out date but sometimes working fine. Can I get help to sort this issue plz...
public void selectCheckDate(String date, WebElement forwardArrow) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date expectedDate = dateFormat.parse(prop.getProperty(date));
String day = new SimpleDateFormat("dd").format(expectedDate);
String month = new SimpleDateFormat("MMMM").format(expectedDate);
String year = new SimpleDateFormat("yyyy").format(expectedDate);
String expectedMonthYear = month + " " + year;
logger.log(Status.INFO, "Expected Month and year: "+expectedMonthYear);
WebDriverWait wait = new WebDriverWait(driver, 20);
String dd1 = "", dd2 = "";
String d1 = null, d2 = null;
boolean flag1 = false;
boolean flag2 = false;
while (true) {
String displayDate1 = driver.findElement(By.xpath("//*[#class='vr-datepicker-LargeStyles__caption--Srrff']/div")).getText();
String displayDate2 = driver.findElement(By.xpath("(//*[#class='vr-datepicker-LargeStyles__caption--Srrff']/div)[2]")).getText();
if (displayDate1.contains(expectedMonthYear)) {
//addWait();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 7; j++) {
d1 = "//*[#id='BODY_BLOCK_JQUERY_REFLOW']/div[14]/div/div/div[2]/div/div/div[2]/div[1]/div[3]/div["
+ i + "]/div[" + j + "]";
boolean ex = isElementExists(d1);
if(ex==true) {
dd1 = driver.findElement(By.xpath(d1)).getText();
if (dd1.equals(day)) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(d1))).click();
//driver.findElement(By.xpath(d1)).click();
flag1 = true;
break;
}
}
}
if (flag1 == true) {
break;
}
}
if (flag1 == true) {
reportPass("Entered date: "+prop.getProperty(date));
break;
}
} else if (displayDate2.contains(expectedMonthYear)) {
//addWait();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 7; j++) {
d2 = "//*[#id='BODY_BLOCK_JQUERY_REFLOW']/div[14]/div/div/div[2]/div/div/div[2]/div[2]/div[3]/div["
+ i + "]/div[" + j + "]";
boolean ex1 = isElementExists(d2);
if(ex1==true) {
dd2 = driver.findElement(By.xpath(d2)).getText();
if (dd2.equals(day)) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(d2))).click();
//driver.findElement(By.xpath(d2)).click();
flag2 = true;
break;
}
}
}
if (flag2 == true) {
break;
}
}
if (flag2 == true) {
reportPass("Entered date: "+prop.getProperty(date));
break;
}
} else {
forwardArrow.click();
}
}
} catch (ParseException e) {
reportFail(e.getMessage());
}
}

Roman Numerals. Could you point out my mistakes further down the road?

Beginner here. This piece of code converts number into roman numerals in multiples of 50 if not 10 if not 9 and down to 0. Methods are so intertwined. Is there something (just at a glance) you could suggest I should avoid doing? Thank You.
public static void main(String[] args) {
System.out.println(fiftyAndAbove(37));
}
public static String nineAndDown(int number) {
String one = "I", five = "V", ten = "X", sum = "";
if(number == 5) {
return five;
} else if(number == 9) {
return one + ten;
}
else if(number > 5) {
for(int i=1; i<=number-5; i++) {
sum += one;
}
return five + sum;
} else {
if(number == 4 ) {
return one + five;
} else
for(int i=1; i <=number; i++) {
sum += one;
}
} return sum;
}
public static String tenAndAbove(int number) {
int remainder = number % 10, numberOftens = number/10;
String ten = "X", sum = "";
if(numberOftens > 0) {
while(numberOftens > 0) {
sum += ten;
numberOftens -= 1;
}
}
return sum + nineAndDown(remainder);
}
public static String fiftyAndAbove(int number) {
int remainder = number % 50, numberOfFifty = number/50;
String fifty = "L", sum = "";
if(numberOfFifty > 0) {
while(numberOfFifty > 0) {
sum += fifty;
numberOfFifty -= 1;
}
}
return sum + tenAndAbove(remainder);
}
Is there something (just at a glance) you could suggest I should avoid doing?
I'd not unnecessarily complicate the logic as with
if(numberOfFifty > 0) {
while(numberOfFifty > 0) {
…
}
}
which is equivalent to
while (numberOfFifty > 0)
{
…
}
You could also have a look at this implementation and see what you prefer:
import java.util.Arrays;
…
public static String fiftyAndAbove(int number)
{
int remainder = number%50, numberOfFifty = number/50;
char [] Ls = new char [numberOfFifty];
Arrays.fill(Ls, 'L');
return new String(Ls) + tenAndAbove(remainder);
}
You have four places like this in your program where you need a string of a character repeated. If you're willing to require a certain Java version or above, you can also use one of the methods described at Java: String - add character n-times; otherwise I'd suggest to use a function to do it.
You could also think about whether you find
String one = "I", five = "V", ten = "X", sum = "";
if(number == 5) {
return five;
} else if(number == 9) {
return one + ten;
}
really better than
if (number == 5) return "V";
if (number == 9) return "IX";

For example, if coins = [1, 2, 5] and N = 11, return true if coins = [3, 77] and N = 100, return

wait online。~
Given a number of coins with different denominations, e.g. [1, 2, 5] and test if they could be used to make up a certain amount (N), assuming you can use unlimited number of coins in each denomination. For example, if coins = [1, 2, 5] and N = 11, return true if coins = [3, 77] and N = 100, return
The idea is use a recursive function (here it will calculate with one first coin vs array of other coins then recursively reduce size of coin array ).
But sr I'm not familiar with Objective-C so I write one using C#. Use should convert it to Objective-C.
bool CanDo(int n, int [] arr)
{
if (arr.Length == 1)
{
if (n % arr[0] == 0)
{
return true;
}
}
else
{
var ls = new List<int>(arr);
ls.RemoveAt(0);
int [] newarr = ls.ToArray(); //Create New array by deleting first element(current calculated element) of old array
for(int i = 0; i <= n/arr[0]; i++)
{
int next_n = n - i * arr[0];
if (next_n == 0)
{
return true;
}
else if (next_n < 0)
{
break;
}
else if(next_n > 0)
{
if( CanDo(next_n, newarr) )
{
return true;
}
}
}
}
return false;
}
This is full code in C# that can print to console first found solution.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static List<string> resultString = new List<string>();
static bool CanDo(int n, int [] arr)
{
if (arr.Length == 1)
{
if (n % arr[0] == 0)
{
resultString.Add(n/ arr[0] + "*" + arr[0]);
return true;
}
}
else
{
var ls = new List<int>(arr);
ls.RemoveAt(0);
int [] newarr = ls.ToArray(); //Create New array by deleting first element of old array
for(int i = 0; i <= n/arr[0]; i++)
{
if (resultString.Count > 0)
{
resultString.RemoveAt(resultString.Count - 1);
}
int next_n = n - i * arr[0];
if (next_n == 0)
{
resultString.Add(i + "*" + arr[0]);
return true;
}
else if (next_n < 0)
{
break;
}
else if(next_n > 0)
{
if (i != 0)
{
resultString.Add(i + "*" + arr[0] + " + ");
}
if( CanDo(next_n, newarr) )
{
return true;
}
}
}
}
return false;
}
static void Main(string[] args)
{
try
{
int[] arr = { 3, 5, 7 };
int N = 20;
resultString = new List<string>();
if (CanDo(N, arr))
{
resultString.ForEach(Console.WriteLine);
Console.Read();
}
else
{
Console.Write("Can't do");
Console.Read();
}
}
catch (Exception ex)
{
//handle exception
}
}
}
}

Why result of GetPageLabels is different from the Adobe Acrobat

I edit page number of pdf in Adobe Acrobat X Pro.
Test PDF
result:
1-FrontCover
2-FrontFold
3-i
4-ii
5-iii
6-1
7-2
8-3
9-4
10-5
11-BackFold
12-BackCover
But this result of GetPageLabels is wrong
page number:
0-FrontCover1
1-FrontFold1
2-FrontFoldi
3-FrontFoldii
4-FrontFoldiii
5-FrontFold1
6-FrontFold2
7-FrontFold3
8-FrontFold4
9-FrontFold5
10-BackFold1
11-BackCover1
C# Code:
objLabels = PdfPageLabels.GetPageLabels(objReader);
TextBox1.Text += "page number:" + Environment.NewLine;
if (objLabels != null) {
for (i = 0; i <= objLabels.Length - 1; i++) {
TextBox1.Text += i + "-" + objLabels(i) + Environment.NewLine;
}
}
How to get the correct result like Adobe Acrobat X Pro?
There is a small bug in PdfPageLabels.GetPageLabels(PdfReader). When encountering a new page label dictionary without a P (prefix) entry, it does not reset the current prefix value:
int pagecount = 1;
String prefix = "";
char type = 'D';
for (int i = 0; i < n; i++) {
if (numberTree.ContainsKey(i)) {
PdfDictionary d = (PdfDictionary)PdfReader.GetPdfObjectRelease(numberTree[i]);
if (d.Contains(PdfName.ST)) {
pagecount = ((PdfNumber)d.Get(PdfName.ST)).IntValue;
}
else {
pagecount = 1;
}
if (d.Contains(PdfName.P)) {
prefix = ((PdfString)d.Get(PdfName.P)).ToUnicodeString();
}
if (d.Contains(PdfName.S)) {
type = ((PdfName)d.Get(PdfName.S)).ToString()[1];
}
else {
type = 'e';
}
}
...
}
You can fix this by adding the following else clause to the if in question:
if (d.Contains(PdfName.P)) {
prefix = ((PdfString)d.Get(PdfName.P)).ToUnicodeString();
}
else
{
prefix = "";
}
Whith this change I get I get
page number:
0 - FrontCover
1 - FrontFold
2 - i
3 - ii
4 - iii
5 - 1
6 - 2
7 - 3
8 - 4
9 - 5
10 - BackFold
11 - BackCover
PS: The same issue is present in the Java iText version, tested in ReadPageLabels.java.
Thank you for helping to solve my problem,
Here is my complete program.
public string[] ReadPageLabel(PdfReader objReader, int intPageCount)
{
PdfDictionary objDictionary ;
Dictionary<int, PdfObject> objTree ;
string[] arrLabels ;
int i ;
char chrLabelKind ;
string strLabelPrefix ;
int intLableNumber ;
//PdfPageLabels is wrong
//arrLabels = PdfPageLabels.GetPageLabels(objReader)
arrLabels = new string[intPageCount];
if (objReader.Catalog.Get(PdfName.PAGELABELS) != null) {
objTree = PdfNumberTree.ReadTree(PdfReader.GetPdfObjectRelease(objReader.Catalog.Get(PdfName.PAGELABELS)));
chrLabelKind = 'D';
strLabelPrefix = "";
intLableNumber = 1;
for (i = 0; i <= intPageCount - 1; i++) {
if (objTree.ContainsKey(i)) { //if reset page number
objDictionary = PdfReader.GetPdfObjectRelease(objTree[i]);
//PdfName.S:Number Kind
if (objDictionary.Contains(PdfName.S)) {
chrLabelKind = ((PdfName)objDictionary.Get(PdfName.S)).ToString()(1);
//PdfName.S:/R,/r,/A,/a,/e,/D,ToString()(1)get alphabet of Index=1
} else {
chrLabelKind = 'e';
}
//PdfName.P:Prefix
if (objDictionary.Contains(PdfName.P)) {
strLabelPrefix = ((PdfString)objDictionary.Get(PdfName.P)).ToUnicodeString();
} else {
strLabelPrefix = "";
}
//PdfName.ST:Start Number
if (objDictionary.Contains(PdfName.ST)) {
intLableNumber = ((PdfNumber)objDictionary.Get(PdfName.ST)).IntValue;
} else {
intLableNumber = 1;
}
}
switch (chrLabelKind) {
case 'R':
//I,II,III
arrLabels[i] = strLabelPrefix + factories.RomanNumberFactory.GetUpperCaseString(intLableNumber);
break;
case 'r':
//i,ii,iii
arrLabels[i] = strLabelPrefix + factories.RomanNumberFactory.GetLowerCaseString(intLableNumber);
break;
case 'A':
//A,B,C
arrLabels[i] = strLabelPrefix + factories.RomanAlphabetFactory.GetUpperCaseString(intLableNumber);
break;
case 'a':
//a,b,c
arrLabels[i] = strLabelPrefix + factories.RomanAlphabetFactory.GetLowerCaseString(intLableNumber);
break;
case 'e':
//no number kind
arrLabels[i] = strLabelPrefix;
break;
default:
//1,2,3
arrLabels[i] = strLabelPrefix + intLableNumber;
break;
}
intLableNumber += 1;
}
} else {
for (i = 0; i <= intPageCount - 1; i++) {
arrLabels[i] = i + 1;
}
}
return arrLabels;
}