populating List<> using Array get wrong numbers - c++

I have simple class structure that has an array part of its fields. I want to store this class in a list. The problem is when adding additional class structures to the list it handles it as if it's a direct update and not referenced.
public class TrayLayout
{
public int[] inerD { get; set; }
public class TrayLayout
{
public int[] inerD { get; set; }
public TrayLayout(int[] inerD)
{
this.inerD = inerD;
}
}
public partial class Form1 : Form
{
public List<TrayLayout> trayL = new List<TrayLayout>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int[] aa = new int[2];
aa[0]=1;
aa[1]=2;
//add the new class to TrayLoayout
trayL.Add(new TrayLayout(aa));
aa[0]=3;
aa[1]=4;
//add the new class to TrayLoayout using input array
trayL.Add(new TrayLayout(aa));
aa[0]=5;
aa[1]=6;
//add the new class to TrayLoayout
trayL.Add(new TrayLayout(aa));
textBox1.Text = "the numbers accepted \n"+ trayL[0].inerD[0].ToString() + " , " +trayL[0].inerD[1].ToString() + " \n" + trayL[1].inerD[0].ToString() + " , " +trayL[1].inerD[1].ToString() + " \n" + trayL[2].inerD[0].ToString() + " , " +trayL[2].inerD[1].ToString() ;
}
I get in TextBoxes it shows the last input 5,6 5,6 5,6 instead of 1,2 3,4 5,6. I must be missing something?

You always refer to the same int array, overwriting the previous values.

You have created 1 ArrayObject aa. And you are overwriting the first 2 values, when you assign 3 and 4. And when you assign 5 and 6 you have overwritten 3 and 4.
Create 3 different arrays or make aa[0] to aa[5].

Assigning the int array to the TrayLayout class does not make a copy. Each instance of the TrayLayout class in your example has a reference to the same array, so when you update it following the call to the TrayLayout constructor, all your instances of TrayLayout see the same values.
Either copy the array internally in the TrayLayout constructor, or (as others are suggesting) use different arrays in the constructor calls.

You need to replace this:
int[] aa = new int[2];
aa[0]=1;
aa[1]=2;
//add the new class to TrayLoayout
trayL.Add(new TrayLayout(aa));
aa[0]=3;
aa[1]=4;
//add the new class to TrayLoayout
trayL.Add(new TrayLayout(aa));
aa[0]=5;
aa[1]=6;
//add the new class to TrayLoayout
trayL.Add(new TrayLayout(aa));
With this:
trayL.Add(new TrayLayout(new int[]{1,2}));
trayL.Add(new TrayLayout(new int[]{3,4}));
trayL.Add(new TrayLayout(new int[]{5,6}));
Edit
You could do it like this:
var start=1;
var end=13;
trayL.Add(new TrayLayout(Enumerable.Range(start,end).ToArray()));

Related

List object get one more item return than the original data set in Blazor WASM

I have a parent component file with one list object.
<h3>Create Movie</h3>
<MovieForm Movie="Movie" NotSelectedGenres="NotSelectedGenres" OnValidSubmit="SaveMovie"/>
#code {
private Movie Movie = new Movie() ;
private List<Genre> NotSelectedGenres = new List<Genre>()
{
new Genre()
{
Id = 1, Name = "Action"
},
new Genre()
{
Id = 2, Name = "Comedy"
},
new Genre()
{
Id = 3, Name = "Drama"
}
} ;
private void SaveMovie()
{
Console.WriteLine("this works") ;
}
}
then I insert child component named 'MovieForm' in it.
And then on debug mode, When I checked the length of 'NotSelectedGenres' it said total 4. (in child component)
[Parameter]
public List<Genre> SelectedGenres { get ; set ; } = new List<Genre>() ;
it has one more with value of 'null' than the original data set.
NotSelectedGenres
_items BlazorMoves.Shared.Entities.Genre[](4)
0 BlazorMoves.Shared.Entities.Genre
1 BlazorMoves.Shared.Entities.Genre
2 BlazorMoves.Shared.Entities.Genre
3 null
length 4
Is this the right thing?
As soon as you add the first item to a List in .NET, it internally allocates an array of size 4. The allocated size increases automatically as required.
the Count property should return the correct number of items in the list, while Capacity returns the current internal size allocated.
List<> docs

Dart group list of items into a different data structure?

I have these classes:
class Car {
String carId;
int yearOfManufacture;
//constructor, fromJson, toJson ...
}
class CarsByYears {
int yearOfManufacture;
List<Car> carList;
//constructor, fromJson, toJson ...
}
And I need to generate a data structure like this based on the given car list only:
List<CarsByYears>
So I get a List<Car> list, and I need to create a List<CarsByYears> list from that. So I need to group the cars by years.
For example I have a List<Car> list which contains these:
Car(1, 1990)
Car(2, 2001)
Car(3, 1990)
I need to create a List<CarsByYears>, which contains 2 CarsByYears object:
The first one is like: yearOfManufacture = 1990 and the carList contains the 1st and the 3rd car object, and the other CarsByYears is contains the 2nd Car object in its carList, and the yearOfManufacture = 2001
How can I do that?
You can use the groupBy function provided by the collection package (which creates a map from a List groping it using a common value as key) and then map the Map entries.
class Car {
final String carId;
final int yearOfManufacture;
Car(this.carId, this.yearOfManufacture);
#override
String toString() => 'Car($carId)';
// Use your constructor and methods
}
class CarsByYears {
final int yearOfManufacture;
final List<Car> carList;
CarsByYears(this.yearOfManufacture, this.carList);
#override
String toString() => 'Year: $yearOfManufacture, Cars: $carList';
// Use your constructor and methods
}
void main() {
var cars = [
Car('1', 2000),
Car('2', 2002),
Car('3', 2000),
Car('4', 2002),
Car('1', 2005)
];
var carsByYear = groupBy<Car, int>(cars, (e) => e.yearOfManufacture)
.entries
.map((e) => CarsByYears(e.key, e.value))
.toList();
print(carsByYear); //Output: [Year: 2000, Cars: [Car(1), Car(3)], Year: 2002, Cars: [Car(2), Car(4)], Year: 2005, Cars: [Car(1)]]
}

Univocity - parse each TSV file row to different Type of class object

I have a tsv file which has fixed rows but each row is mapped to different Java Class.
For example.
recordType recordValue1
recordType recordValue1 recordValue2
for First row I have follofing class:
public class FirstRow implements ItsvRecord {
#Parsed(index = 0)
private String recordType;
#Parsed(index = 1)
private String recordValue1;
public FirstRow() {
}
}
and for second row I have:
public class SecondRow implements ItsvRecord {
#Parsed(index = 0)
private String recordType;
#Parsed(index = 1)
private String recordValue1;
public SecondRow() {
}
}
I want to parse the TSV file directly to the respective objects but I am falling short of ideas.
Use an InputValueSwitch. This will match a value in a particular column of each row to determine what RowProcessor to use. Example:
Create two (or more) processors for each type of record you need to process:
final BeanListProcessor<FirstRow> firstProcessor = new BeanListProcessor<FirstRow>(FirstRow.class);
final BeanListProcessor<SecondRow> secondProcessor = new BeanListProcessor<SecondRow>(SecondRow.class);
Create an InputValueSwitch:
//0 means that the first column of each row has a value that
//identifies what is the type of record you are dealing with
InputValueSwitch valueSwitch = new InputValueSwitch(0);
//assigns the first processor to rows whose first column contain the 'firstRowType' value
valueSwitch.addSwitchForValue("firstRowType", firstProcessor);
//assigns the second processor to rows whose first column contain the 'secondRowType' value
valueSwitch.addSwitchForValue("secondRowType", secondProcessor);
Parse as usual:
TsvParserSettings settings = new TsvParserSettings(); //configure...
// your row processor is the switch
settings.setProcessor(valueSwitch);
TsvParser parser = new TsvParser(settings);
Reader input = new StringReader(""+
"firstRowType\trecordValue1\n" +
"secondRowType\trecordValue1\trecordValue2");
parser.parse(input);
Get the parsed objects from your processors:
List<FirstRow> firstTypeObjects = firstProcessor.getBeans();
List<SecondRow> secondTypeObjects = secondProcessor.getBeans();
The output will be*:
[FirstRow{recordType='firstRowType', recordValue1='recordValue1'}]
[SecondRow{recordType='secondRowType', recordValue1='recordValue1', recordValue2='recordValue2'}]
Assuming you have a sane toString() implemented in your classes
If you want to manage associations among the objects that are parsed:
If your FirstRow should contain the elements parsed for records of type SecondRow, simply override the rowProcessorSwitched method:
InputValueSwitch valueSwitch = new InputValueSwitch(0) {
#Override
public void rowProcessorSwitched(RowProcessor from, RowProcessor to) {
if (from == secondProcessor) {
List<FirstRow> firstRows = firstProcessor.getBeans();
FirstRow mostRecentRow = firstRows.get(firstRows.size() - 1);
mostRecentRow.addRowsOfOtherType(secondProcessor.getBeans());
secondProcessor.getBeans().clear();
}
}
};
The above assumes your FirstRow class has a addRowsOfOtherType method that takes a list of SecondRow as parameter.
And that's it!
You can even mix and match other types of RowProcessor. There's another example here that demonstrates this.
Hope this helps.

Spring Data Neo4j Map query result to Non entity POJOs

I am using spring-data-neo4j. I want the results of the query to be mapped to a non-entity POJO.
This is how the repository looks like
public interface CategoryRepository extends GraphRepository<Category> {
#Query("Match (:Client {email: {clientEmail}})-[:client]->()" + "-[:owns]->()-[:had]->(a:visit)-[:to]->()-[:category]->(b)"
+ " where a.lastPredictionTime > {startTime} and a.lastPredictionTime < {endTime}" + " with Distinct b.name as category, sum(a.timeSpent) as sum order by sum desc"
+ " return collect({category: category, timeSpent: sum})[{start}..{end}]")
List<CountDetailsByDate> getTopCategoriesByTimeSpent(#Param("clientEmail") String clientEmail, #Param("start") int start, #Param("end") int end,
#Param("startDate") long startDate, #Param("endDate") long endDate);
}
The CountDetailsByDate object is neither a node entity nor a relationship entity, I want the result of the query to be mapped to it. Is there any way to do that?
You should create a CountDetailsByDate class and annotate it with #QueryResult.
You can either define it as an inner class in your CategoryRepository repository interface or you can create it somewhere else.
The inner-class code will be like this :
public interface CategoryRepository extends GraphRepository<Category> {
#Query("Match (:Client {email: {clientEmail}})-[:client]->()" + "-[:owns]->()-[:had]->(a:visit)-[:to]->()-[:category]->(b)"
+ " where a.lastPredictionTime > {startTime} and a.lastPredictionTime < {endTime}" + " with Distinct b.name as category, sum(a.timeSpent) as sum order by sum desc"
+ " return collect({category: category, timeSpent: sum})[{start}..{end}]")
List<CountDetailsByDate> getTopCategoriesByTimeSpent(#Param("clientEmail") String clientEmail, #Param("start") int start, #Param("end") int end,
#Param("startDate") long startDate, #Param("endDate") long endDate);
}
#QueryResult
class CountDetailsByDate {
// class variables and ...
}
If you choose to create a separate class , make sure you add the package path to component scan of your Neo4j Config class. It will be something like this :
#Configuration
#EnableTransactionManagement
#EnableNeo4jRepositories(basePackages = {"XXX-PATH-TO-Repo-packages"})
#ComponentScan(basePackages = "YYY-PATH-TO-YOUR-CLASS-Package")
public class Neo4jConfig extends Neo4jConfiguration {
....
}
Hope this will help.

How to refer PageReference method from apex test class

I am new to apex, I have created a button to call the apex class through the visual force page.
Here is my visual force page code.
<apex:page standardController="Opportunity"
extensions="myclass"
action="{!autoRun}">
</apex:page>
Here is my apex class.
public class myclass {
private final Opportunity o;
String tmp;
public myclass(ApexPages.StandardController stdController) {
this.o = (Opportunity)stdController.getRecord();
}
public PageReference autoRun() {
String theId = ApexPages.currentPage().getParameters().get('id');
for (Opportunity o:[select id, name, AccountId, from Opportunity where id =:theId]) {
//Create the Order
Order odr = new Order(
OpportunityId=o.id
,AccountId = o.AccountId
,Name = o.Name
,EffectiveDate=Date.today()
,Status='Draft'
);
insert odr;
tmp=odr.id;
}
PageReference pageRef = new PageReference('/' + tmp);
pageRef.setRedirect(true);
return pageRef;
}
}
I want to create test class. I don't know how to refer PageReference autoRun() method from test class. Guys need help if some one can tell me about test class of this apex class.
You will need to configure the StandardController for the inserted Opportunity. Then pass the StandardController to pass to the constructor before calling the method to test.
E.g.
public static testMethod void testAutoRun() {
Opportunity o = new Opportunity();
// TODO: Populate required Opportunity fields here
insert o;
PageReference pref = Page.YourVisualforcePage;
pref.getParameters().put('id', o.id);
Test.setCurrentPage(pref);
ApexPages.StandardController sc = new ApexPages.StandardController(o);
myclass mc = new myclass(sc);
PageReference result = mc.autoRun();
System.assertNotEquals(null, result);
}