print list only printing last item - loops

This is the code:
public static void main(String[] args) {
listOne.add(new Data("Credit Card", "100.00", "1"));
listOne.add(new Data("Medical", "200.00", "2"));
listOne.add(new Data("Alcohol", "100.00", "3"));
listOne.add(new Data("Credit Card", "50.00", "4"));
listOne.add(new Data("Medical", "200.00", "5"));
listOne.add(new Data("Gas", "50.00", "6"));
listOne.add(new Data("Tabacco", "50.00", "7"));
listOne.add(new Data("Gas", "50.00", "8"));
for( int c = 0; c < listOne.size(); c++){
Data d = listOne.get(c);
System.out.println(d.getName() + " " + d.getSpent() + " " + d.getIndex());
}
This is the output:
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
It is only printing the last entry, why? I just can not see what is wrong. I am sure it is right in front of me. Any help would be appreciated.
Thanks,
Rich

Related

First-In-First-Out Stock trading - calculate cumulative P/L

I want a sql-server query to calculate cumulative P/L on stock trading (FIFO based calculation).
Input table :
EXECTIME
share_name
Quantity
Price
Buy/Sell
2013-01-01 12:25
abc
100
100
B
2013-01-01 12:26
abc
10
102
S
2013-01-01 12:27
abc
10
102
S
2013-01-01 12:28
abc
10
95
S
2013-01-01 12:29
abc
10
99
S
2013-01-01 12:30
abc
10
105
S
2013-01-01 12:31
abc
100
102
B
2013-01-01 12:32
abc
150
101
S
OUTPUT :
EXECTIME
Cumualative P/L
Winning Streak
Lossing Streak
2013-01-01 12:26
20
1
0
2013-01-01 12:27
40
1
0
2013-01-01 12:28
-10
0
1
2013-01-01 12:29
-20
0
2
2013-01-01 12:30
30
1
0
2013-01-01 12:32
-20
0
1
Explanation :
1st row - 10 shares sold at 102 which were purchased at 100. So profit = (102-100) * 10 = 20
6th row - 150 shares sold at 101,
50 were purchased at 100 - 1st row( 50 already sold above, 50 left)
100 were purchaed at 102 - 7th row
150 * 101 - [(50 * 100)+(100 * 102)] = -50
cumaltive p/l = 30 + (-50) = -20
Winning streak - 1 for positive
Lossing streak - 1,2,... for continuous loss. reset again after profit

Calculating sums conditionally on data values

I have quite a large conflict dataset (71 million observations) with many variables and date (daily).
This is from the GDELT project. For each day, there is a target country and a source country of aggression. For example, on 1 January 2000, many countries were engaged in aggressive behaviour against others or themselves.
It looks like this:
clear
input long date_01 str18 source_01 str19 target_01 str4 cameocode_01
20000101 "AFG" "AFGGOV" "2"
20000101 "AFG" "AFGGOV" "8"
20000101 "AFG" "ARE" "3"
20000101 "AFG" "CVL" "4"
20000101 "AFG" "GOV" "10"
20000101 "AFG" "GOV" "4"
20000101 "AFGGOV" "kasUAF" "3"
20000101 "FRA" "kasUAF" "8"
20000101 "AFG" "IGOUNO" "3"
20000101 "AFG" "IND" "4"
20000101 "AFG" "IND" "12"
20000102 "AFG" "IND" "19"
end
Variable date_01 is the day, source_01 is the country that initiated aggression, target_01 is the victim, and cameocode_01 is the variable of concern which states the degree of hostility or cooperation. If the number is between 10 and 20, that is a hostility event, with 20 being the more hostile. If the number is between 0 and 9, that indicates cooperation (good event), with 9 being the friendliest.
I have managed with help from this platform to isolate the event per country, namely to isolate the cameo codes involving a certain amount of countries (I am interested in 30) to follow their conflict evolution through time.
I did the following:
foreach c in AFG IND ARE {
generate ind_`c' = cameocode_01 if strmatch(source_01, "`c'") | ///
strmatch(target_01, "`c'")
}
This yields what is desired:
date source target cameocode ind_AFG ind_IND ind_ARE
1. 20000101 AFG AFGGOV 2 2
2. 20000101 AFG IND 4 4 4
3. 20000101 AFG AFGGOV 8 8
4. 20000101 AFG ARE 3 3 36
5. 20000101 AFG CVL 4 4
6. 20000101 AFG GOV 10 10
7. 20000101 AFG GOV 4 4
8. 20000101 AFGGOV kasUAF 3
9. 20000101 AFGGOV kasUAF 8
10. 20000101 AFG IRQ 12 12
11. 20000102 AFG IND 19 19 19
Whenever a given country is involved as either recipient or initiator, I create a new variable isolating that specific event and its intensity for a given date.
What I want to do now is to be able to create a standardized measure or ratio where for each date, the sum of conflict measures (numbers from 10 to 20) are divided to by the sum of the cooperation measures (numbers from 1 to 9) for each country.
So my desired output for this table above for AFG 20000101 (5th column) would be:
(12+19) / (2+4+8+3+4+4)
I would like to repeat this for each date for each of the variables ind_COUNTRY CODE to have one number per day per country.
Is there a way to do this?
This appears to be the key trick you seek.
clear
input long date str6 source float cameocode
20000101 "AFG" 2
20000101 "AFG" 4
20000101 "AFG" 8
20000101 "AFG" 3
20000101 "AFG" 4
20000101 "AFG" 10
20000101 "AFG" 4
20000101 "AFGGOV" 3
20000101 "AFGGOV" 8
20000101 "AFG" 12
end
egen num = total(cond(cameocode >= 10, cameocode, .)), by(date source)
egen den = total(cond(cameocode < 10, cameocode, .)), by(date source)
generate wanted = num / den
sort date source
list, sepby(source)
+------------------------------------------------------------+
| date source target cameoc~e num den wanted |
|------------------------------------------------------------|
1. | 20000101 AFG IND 4 22 25 .88 |
2. | 20000101 AFG GOV 4 22 25 .88 |
3. | 20000101 AFG AFGGOV 2 22 25 .88 |
4. | 20000101 AFG AFGGOV 8 22 25 .88 |
5. | 20000101 AFG IRQ 12 22 25 .88 |
6. | 20000101 AFG GOV 10 22 25 .88 |
7. | 20000101 AFG CVL 4 22 25 .88 |
8. | 20000101 AFG ARE 3 22 25 .88 |
|------------------------------------------------------------|
9. | 20000101 AFGGOV kasUAF 8 0 11 0 |
10. | 20000101 AFGGOV kasUAF 3 0 11 0 |
+------------------------------------------------------------+
See sections 9 and 10 in this paper for technique. The essential idea is that many egen functions allow expressions as arguments, which can be more complicated than just variable names. Here we use cond() to specify that only values in certain intervals should be totalled.
A less transparent but less wasteful recipe in terms of creation of variables would run something like
egen wanted = !code for numerator!
egen den = !code for denominator!
replace wanted = wanted / den
drop den

How can I fix this bubble sort function in C?

I am passing an array of flight information and flight count to a sorting function. Within the flight array are flight id's, for example (H100.15005), and my goal is to sort the flight information ascending order based on the flight ids. How can I fix the bubble sort function?
Language: C Platform: Virtual machine on Mac OS X OS: Ubuntu (64-bit)
16.04 LTS Editor: Vim 7.4 Constraints: Must use basic sorting algorithm.
Here is the before and after sorting outputs along with the code:
Initial Flights
Flight Id From Dest Depart Avail Unit Price
H100.15005 SAT HOU 08:00 4 65.00
H111.15009 SAT HOU 17:00 10 65.00
H555.15022 SAT DFW 08:00 70 70.00
H444.15015 ATL NYC 08:00 10 130.00
H200.15010 ATL HOU 08:00 20 120.00
H222.15005 HOU ATL 10:00 15 125.00
H333.15010 ATL NYC 13:00 20 130.00
H444.15001 ATL NYC 08:00 10 130.00
H100.15006 SAT HOU 08:00 12 65.00
H333.15012 ATL NYC 12:55 60 130.00
H666.15020 NYC ATL 01:45 50 140.00
Sorted Flights
Flight Id From Dest Depart Avail Unit Price
H100.15005 SAT HOU 08:00 4 65.00
H111.15009 SAT HOU 17:00 10 65.00
H555.15022 SAT DFW 08:00 70 70.00
H444.15015 ATL NYC 08:00 10 130.00
H200.15010 ATL HOU 08:00 20 120.00
H222.15005 HOU ATL 10:00 15 125.00
H333.15010 ATL NYC 13:00 20 130.00
H444.15001 ATL NYC 08:00 10 130.00
H100.15006 SAT HOU 08:00 12 65.00
H333.15012 ATL NYC 12:55 60 130.00
H666.15020 NYC ATL 01:45 50 140.00
void sortFlights(Flight flightM[], int iFlightCnt) {
int i;
int j;
Flight flightIdTemp;
for(i = 0; i < (iFlightCnt - 1); i++) {
for(j = (iFlightCnt - 1); j > i; j--) {
if(flightM[j-1].szFlightId > flightM[j].szFlightId) {
flightIdTemp = flightM[j-1];
flightM[j-1] = flightM[j];
flightM[j] = flightIdTemp;
}
}
}
}
The variable szFlightId is probably a character string and you want to compare the content of the two strings. This does not work with the > operator in C which will only compare the memory addresses. You need to use the function strcmp() instead.
if (strcmp(flightM[j-1].szFlightId, flightM[j].szFlightId) > 0)
(Actually we do not know the type, but the prefix sz has often been used to mark zero terminated strings. Some Hungarian developer at Microsoft introduced this convention which is therefore called Hungarian Notation.)
void sortFlights(Flight flightM[], int iFlightCnt) {
int i;
int j;
Flight flightIdTemp;
for(i = 0; i < (iFlightCnt - 1); i++) {
for(j = (iFlightCnt - 1); j > i; j--) {
if(strcmp(flightM[j-1].szFlightId, flightM[j].szFlightId) > 0) {
flightIdTemp = flightM[j-1];
flightM[j-1] = flightM[j];
flightM[j] = flightIdTemp;
}
}
}
}

How to transform a CSV file data in Apache camel

I want to transform some field's data in specific rows in csv file.I tried the following .
1).Using csv marshaling and unmarshaling I achieved it ,but the output CSV is not coming in proper order even though I sent list of maps (i.e List) .
following is my program
from("file:E://camelinput//?noop=true")
.unmarshal(csv)
.convertBodyTo(List.class)
.process(new Processor() {
#Override
public void process(Exchange msg) throws Exception {
List<List<String>> data = (List<List<String>>) msg.getIn().getBody();
List<Map<String,Object>> newdata=new ArrayList<Map<String,Object>>();
Map<String,Object> map=null;
for (List<String> line : data) {
System.out.println(line.size());
map=new HashMap<String,Object>();
if("1502873".equals(line.get(3))){
line.set(18, "Y");
}
// newdata.add(line);
int count=0;
for(Object field:line){
// System.out.println("line.get(count) "+line.get(count));
map.put(String.valueOf(count),field);
count++;
}
newdata.add(map);
}
msg.getIn().setBody(newdata);
}
})
.marshal().csv().convertBodyTo(List.class)
.to("file:E://camelout").end();
2)And again I tried Using .split(body()) and trying to process each row(i.e with out using Marshaling I am trying),but it is taking very huge time and getting terminated with some Interrupted exception.
following is the code
from("file:E://camelinput//?noop=true")
.unmarshal(csv)
.convertBodyTo(List.class)
.split(body())
.process(new Processor() {
#Override
public void process(Exchange msg) throws Exception {
List<String> rec= new ArrayList<String>();
if("1502873".equals(rec.get(3))){
rec.set(18, "Y");
}
String dt=rec.toString().trim().replace("[","").replace("]", "");
msg.getIn().setBody(dt, String.class);
}
})
.to("file:E://camelout").end();
following is my sample Csv
25 STANDARD N 1435635 415 1087 15904 7 null 36 Cross Mechanical Pencil, Lead and Eraser, 0.5 mm 2 23162 116599 7/7/2015 15:45 N 828
25 STANDARD N 1435635 415 1087 15905 8 null 36 Jumbo Ballpoint and Selectip Refill, Medium, Black 4 23163 116599 7/7/2015 15:45 N 829
25 STANDARD N 1435635 415 1087 15906 1 3487 null 598 Copier Toner, Cannon 220 23164 116599 7/7/2015 15:45 N 830
25 STANDARD N 1435635 415 1087 15907 2 3495 null 823 Envelopes 27 23165 116599 7/7/2015 15:45 N 831
25 STANDARD N 1435635 415 1087 15908 3 3513 null 789 Legal Pads, 8 1/2 x 11 3/4" White" 30 23166 116599 N 832
25 STANDARD N 1435635 415 1087 15909 4 3577 null 791 Paper Clips 5 23167 116599 7/7/2015 15:45 N 833
31 STANDARD N 1574437 415 1087 15910 5 null 36 Clic Stic Pen, Fine, Black 0.72 23168 116599 7/7/2015 15:45 N 834
31 STANDARD N 1574437 557 1233 15911 6 null 36 Laser Cards, 50 Note Cards/Envelopes, 4-1/4 inch x 5-1/2 inch, White 21.58 23169 116599 7/7/2015 15:45 N 835
31 STANDARD N 1574437 578 1275 15912 1 201 null 32 Keyboard - 101 Key 20.82 23170 116599 7/7/2015 15:45 N 836
25 STANDARD N 1574437 147 2033 15913 1 225 null 30 Monitor - 19" 225.39 23171 116599 7/7/2015 15:45 N 837
1314 STANDARD N 1502873 22 2199 16287 1 628 null 1 Envoy Deluxe Laptop 822.87 23545 116599 7/7/2015 15:45 N 838
1314 STANDARD N 1502873 22 2199 16288 1 151 null 91 Envoy Standard Laptop 1283.44 23546 116599 7/7/2015 15:45 N 839
7653 STANDARD N 1502873 22 2199 16289 2 606 null 1 Battery - Extended Life 28 23547 116599 7/7/2015 15:45 N 840
7652 STANDARD N 1502873 21 459 16290 1 2157 null 1 Envoy Laptop - Rugged 1525.02 23548 116599 7/7/2015 15:45 N 841
1314 STANDARD N 1502873 3 1594 16291 1 251 null 32 RAM - 256MB 51.25 23549 116599 7/7/2015 15:45 N 842
7654 STANDARD N 1502873 22 2199 16292 1 606 null 1 Battery - Extended Life 28 23550 116599 7/7/2015 15:45 N 843
7652 STANDARD N 1502873 21 459 16293 1 247 null 30 Monitor - 17" 225.39 23551 116599 7/7/2015 15:45 N 844
1704 STANDARD N 1502873 41 2200 16294 2 225 null 30 Monitor - 19" 225.39 23552 116599 7/7/2015 15:45 N 845
7658 STANDARD N 1502873 21 460 16295 1 201 null 32 Keyboard - 101 Key 20.82 23553 116599 7/7/2015 15:45 N 846
I have large Csv files which contains hundreds of thousands of rows.
I think your solution 1 might be overly complex if you only want to alter values in csv and output it it back in the same order. Just edit fields in the original List and marshall it back to file.
I've made here assumption that your data was actually delimited by tabs rather than random amount of spaces in your example but I've included the CsvDataFormat that I used. Code uses camel-core and camel-csv version 2.15.3.
public void configure() {
CsvDataFormat csv = new CsvDataFormat();
csv.setDelimiter('\t'); // Tabs
csv.setQuoteDisabled(true); // Otherwise single quotes will be doubled.
from("file://src/data?fileName=data.csv&noop=true&delay=15m")
.unmarshal(csv)
.convertBodyTo(List.class)
.process(new Processor() {
#Override
public void process(Exchange msg) throws Exception {
List<List<String>> data = (List<List<String>>) msg.getIn().getBody();
for (List<String> line : data) {
// Checks if column two contains text STANDARD
// and alters its value to DELUXE.
if ("STANDARD".equals(line.get(1))) {
System.out.println("Original:" + line);
line.set(1, "DELUXE");
System.out.println("After: " + line);
}
}
}
}).marshal(csv).to("file://src/data?fileName=out.csv")
.log("done.").end();
}
The problem is that you are processing single line in single thread. If parallel processing correct for you, try to use ThreadPool.
<camel:camelContext id="camelContext">
.....
<camel:threadPoolProfile id="customThreadPoolProfile"
defaultProfile="true"
poolSize="{{split.thread.pool.size}}"
maxPoolSize="{{split.thread.max.pool.size}}"
maxQueueSize="{{split.thread.max.queue.size}}">
</camel:threadPoolProfile>
</camel:camelContext>
And upgrade split
.split(body().tokenize("\n"))
.streaming()
.parallelProcessing()
.executorServiceRef("customThreadPoolProfile")
.....
.end()

struct elements erasing itself

Ok so I am reading some things from files with this code:
for (i=0; i<start;i++)
{
filename=files[i];
if((fp=fopen(filename, "r"))==NULL)
{
printf("unable to open %s\n", filename);
exit(1);
}
while(fgets(buffer, sizeof(buffer), fp) !=NULL)
{
d[counter].id=atoi(strtok(buffer, del));
strcpy(buffer2, strtok(NULL, del));
len=strlen(buffer2);
if(buffer2[len-1]=='\n')
buffer2[len-1]='\0';
strcpy(d[counter].name, buffer2);
counter++;
}
token = strtok (filename, del1);
holder=token;
token = strtok (NULL, del1); /* section*/
token2 = strtok(holder, del2);
token2 = strtok(NULL, del2); /*course name */
for(x=z;x<counter;x++)
{
d[x].section=atoi(token);
printf("%d ", d[x].section);
strcpy(d[x].course, token2);
printf("%s %d %s %d\n", d[x].course, d[x].section, d[x].name, d[x].id);
}
z=counter;
}
Struct definition:
struct student {
char course[8];
int section;
char name[19];
int id;
};
Everything prints fine except for the "section" in the struct, for some reason the elements makes itself 0 after a certain amount.
Here is the output:
1 CSE1325 1 Sally 3233
1 CSE1325 1 George 9473
2 CSE1325 2 Tom 1234
2 CSE1325 2 Ralph 3540
2 CSE1325 2 Mary 5678
1 CSE2312 1 Tom 1234
1 CSE2312 1 Ralph 3540
1 CSE2312 1 Mary 5678
1 CSE2315 1 Tom 1234
1 CSE2315 1 Ralph 3540
1 CSE2315 1 Mary 5678
2 CSE2315 2 Sally 3233
2 CSE2315 2 George 9473
4 ENGL1301 0 Tom 1234
4 ENGL1301 0 Sally 3233
4 ENGL1301 0 Ralph 3540
4 ENGL1301 0 Mary 5678
4 ENGL1301 0 George 9473
1 HIST1311 0 Tom 1234
1 HIST1311 0 Sally 3233
1 HIST1311 0 Ralph 3540
1 HIST1311 0 Mary 5678
1 HIST1311 0 George 9473
5 MATH1426 0 Sally 3233
5 MATH1426 0 George 9473
This is the expected output:
1 CSE1325 1 Sally 3233
1 CSE1325 1 George 9473
2 CSE1325 2 Tom 1234
2 CSE1325 2 Ralph 3540
2 CSE1325 2 Mary 5678
1 CSE2312 1 Tom 1234
1 CSE2312 1 Ralph 3540
1 CSE2312 1 Mary 5678
1 CSE2315 1 Tom 1234
1 CSE2315 1 Ralph 3540
1 CSE2315 1 Mary 5678
2 CSE2315 2 Sally 3233
2 CSE2315 2 George 9473
4 ENGL1301 4 Tom 1234
4 ENGL1301 4 Sally 3233
4 ENGL1301 4 Ralph 3540
4 ENGL1301 4 Mary 5678
4 ENGL1301 4 George 9473
1 HIST1311 1 Tom 1234
1 HIST1311 1 Sally 3233
1 HIST1311 1 Ralph 3540
1 HIST1311 1 Mary 5678
1 HIST1311 1 George 9473
5 MATH1426 5 Sally 3233
5 MATH1426 5 George 9473
See how the numbers match? But for mine it doesn't, when I print d[x].section in the for loop as a standalone it prints the correct thing, but when I use it in that combined print statement for some reason it prints out 0 when reaching ENGL1301.
The course number can be eight characters, and strings in C are by convention null-terminated. Since your declaration is char course[8], when there are eight characters in the course number, the terminating null is being put off the end of course which lands in the section number, making it zero.
Declaring char course[9] should do the trick.
The 0 is almost certainly the null terminator from this value (and the other values of the same length):
"ENGL1301"
This 8 character string is 9 characters when you include the null terminator at the end of the string. In this case, the null terminator is being written past the end of the string, which happens to be where the section is stored.
To fix this, declare course as char course[9]

Resources