C++ Data Parsing query - c++

Hello guys i hope you could enlighten me with this issue i am facing!
Initial Output:
The sample text file is below and the format is as follow (Item Desc:Price:Quantity:Date).
STRAW:10:10:11NOV1991
BARLEY:5.10:5:19OCT1923
CHOCOLATE:50:50:11NOV1991
I am required to print out a daily summary report of the total amt of sales on that day. Based on the sample above, the result will be on 11 NOV 1991 the total amt of sales(2 items) will be 60 while on 19OCT1923 the total amt of sales(1 item) will be 5.
Desired Output:
11Nov1991 Total amt of sales:60
19Oct1923 Total amt of sales:5
My question is, how do i generate the code to show only one unique date with the total amount of sales? I have created a loop to check if that a certain year exist for testing purposes but it isn't working. I want it to be able to iterate through a file and check if a certain year exist and if it exist already, the next vector element that has the same year won't be written to a file but instead only the item price will be added. Below is the code i am trying to implement.
ifstream readReport("DailyReport.txt");
ofstream writeDailyReport("EditedDailyReport.txt");
string temp1 = "";
//Read from empty report.txt
while(getline(readReport,temp1))
{
for(int i=0; i < itemDescVec.size(); i++)
{
stringstream streamYearSS;
streamYearSS << itemDescVec[i].dateYear;
string stringYear = streamYearSS.str();
size_t found1 = temp1.find(stringYear);
//If can find year
if (found1 != string::npos )
{
cout << "Can find" << endl;
}
//If cannot find year
else if (found1 == string::npos )
{
cout << "Cannot find" << endl;
writeDailyReport << itemDescVec[i].itemDescription << ":" << itemDescVec[i].unitPrice << ":"
<< itemDescVec[i].quantity << ":" << itemDescVec[i].dateDay << "/" << itemDescVec[i].dateMonth << "/" << itemDescVec[i].dateYear
<< endl;
}
}
}
readReport.close();
writeDailyReport.close();
remove("DailyReport.txt");
rename("EditedDailyReport.txt", "DailyReport.txt");

It would be better to use your own object to store the data - then you can write, for example, salesRecord.quantity (or salesRecord.getQuantity() if you have written a getter) instead of salesrecord.at(2). This is a lot more readable and is better practice than remembering that 2 = quantity (etc.).
Now as to your actual question... I would say something like this:
Iterate over the list. For each item:
Check if the date of the item has already been added to your new list.
If the date does not already exist, simply add the item in its entireity.
If it does already exist, edit the existing item such that previousQuantity += quantityToAdd
On the sorted list
BARLEY:5.10:5:19OCT1923
STRAW:10:10:11NOV1991
CHOCOLATE:50:50:11NOV1991
this would work as follows:
Try to add barley data - nothing for that date so far, so add it:
19OCT1923 - 5 units
Try to add strawberry data - nothing for that date so far, so add it:
19OCT1923 - 5 units
11NOV1991 - 10 units
Try to add chocolate data - 11NOV1991 already exists, so add 50 to the 10 that's already there:
19OCT1923 - 5 units
11NOV1991 - 60 units

Related

Split row in multiple other rows in Power Bi based on a division of a number

In Power BI Desktop i have a table from an excel file and i want to split a row based on a division between the value of a specific column and a default number.
In more details lets assume tha we have a table like this :
if the default value we want to devide column Amount is 50,then the desirable result would be something like that :
Do you have any idea how can i implement that in Power query editor or with dax?
Thanks
Tested this in Power Query for Excel, but hopefully should work for you in Power BI too. If you create a function like:
divisionToList = (numberToDivide as number, numberToDivideBy as number) as list =>
let
divisionResult = numberToDivide / numberToDivideBy,
isResultValid = (divisionResult >= 0) and (Number.Mod(divisionResult, 1) = 0),
errorIfInvalid = Error.Record("Cannot create a list with " & Text.From(divisionResult) & " items", Number.ToText(numberToDivide) & " / " & Number.ToText(numberToDivideBy) & " = " & Text.From(divisionResult), null),
listOrError = if isResultValid then List.Repeat({divisionResult}, divisionResult) else error errorIfInvalid
in listOrError,
It should divide two numbers and return a list of length d in which each element is d (d is the result of the division). This list can then, in the context of a table, be expanded into new rows.
There is some basic error handling in the function for cases where the division yields a problematic number (since you can't have a list with, for example, 5.1 elements or -1 elements). You can change/remove this handling if necessary.
I think this code below takes me from your first image to your second image -- and hopefully will give you some idea on how to go about achieving this.
let
mockData = Table.FromColumns({{200, 400}, {"A", "B"}}, type table [Amount = number, Description = text]),
defaultValue = 50, // Not sure what logic is required for arriving at this figure, so have simply assigned it.
divisionToList = (numberToDivide as number, numberToDivideBy as number) as list =>
let
divisionResult = numberToDivide / numberToDivideBy,
isResultValid = (divisionResult >= 0) and (Number.Mod(divisionResult, 1) = 0),
errorIfInvalid = Error.Record("Cannot create a list with " & Text.From(divisionResult) & " items", Number.ToText(numberToDivide) & " / " & Number.ToText(numberToDivideBy) & " = " & Text.From(divisionResult), null),
listOrError = if isResultValid then List.Repeat({divisionResult}, divisionResult) else error errorIfInvalid
in listOrError,
invokeFunction = Table.TransformColumns(mockData, {{"Amount", each divisionToList(_, defaultValue), type list}}),
expanded = Table.ExpandListColumn(invokeFunction, "Amount")
in
expanded

How can I use C++ to update an SQLite row relative to its original value?

I am trying to update a row in a table in an SQLite database using C++, but I want to update it relative to its current value.
This is what I have tried so far:
int val=argv[2];
string bal = "UPDATE accounts SET balance = balance + " + argv[1] + "WHERE account_id = " + bal + argv[2];
if (sqlite3_open("bank.db", &db) == SQLITE_OK)
{
sqlite3_prepare( db, balance.c_str(), -1, &stmt, NULL );//preparing the statement
sqlite3_step( stmt );//executing the statement
}
So that the first parameter is the account_id, and the second parameter is the current balance.
However, this does not work. What can I do to have the database successfully update?
Thank you!
EDIT: Sorry for the confusion. The primary situation is having a table with many entries, each with a unique account id. For example, one has an id of 1 with a balance of 5.
If I run this program with the parameters "1 5", the balance should now be 10. If I run it again with "1 7", it should be 17.
You cannot use the + operator to concatenate C-style strings and string literals. A quick and dirty fix:
string bal = string("UPDATE accounts SET balance = balance + ") + argv[1] + string( " WHERE account_id = " ) + argv[2];

Database table not being updated

I have been struggling with this piece of code. Everything is being updated except my items table in the database. Need the sales part to be plus 1 each time someone makes a purchase.
$setQuery = '';
if($extended) {
$setQuery = " `status` = 'extended_buy', ";
}
$mysql->query("
UPDATE `items`
SET `sales` = `sales` + 1,
$setQuery
`earning` = `earning` + '".sql_quote($price)."'
WHERE `id` = '".intval($item['id'])."'
");
return true;
}
You will need to use Subquery for the same
It would be somewhat like this
SET sales = (From items where WHERE id = '".intval($item['id']) + 1,
You will need to pull its value and then Add it.
In other case you can pick it in variable and update it.

How do I take already calculated totals that are in a loop and add them together?

I created this program in Python 2.7.3
I did this in my Computer Science class. He assigned it in two parts. For the first part we had to create a program to calculate a monthly cell phone bill for five customers. The user inputs the number of texts, minutes, and data used. Additionaly, there are overage fees. $10 for every GB of data over the limit, $.4, per minute over the limit, and $.2 per text sent over the limit. 500 is the limit amount of text messages, 750 is the limit amount of minutes, and 2 GB is the limit amount of data for the plan.
For part 2 of the assignment. I have to calculate the total tax collected, total charges (each customer bill added together), total goverment fees collected, total customers who had overages etc.
Right now all I want help on is adding the customer bills all together. As I said earlier, when you run the program it prints the Total bill for 5 customers. I don't know how to assign those seperate totals to a variable, add them together, and then eventually print them as one big variable.
TotalBill = 0
monthly_charge = 69.99
data_plan = 30
minute = 0
tax = 1.08
govfees = 9.12
Finaltext = 0
Finalminute = 0
Finaldata = 0
Finaltax = 0
TotalCust_ovrtext = 0
TotalCust_ovrminute = 0
TotalCust_ovrdata = 0
TotalCharges = 0
for i in range (1,6):
print "Calculate your cell phone bill for this month"
text = input ("Enter texts sent/received ")
minute = input ("Enter minute's used ")
data = input ("Enter Data used ")
if data > 2:
data = (data-2)*10
TotalCust_ovrdata = TotalCust_ovrdata + 1
elif data <=2:
data = 0
if minute > 750:
minute = (minute-750)*.4
TotalCust_ovrminute = TotalCust_ovrminute + 1
elif minute <=750:
minute = 0
if text > 500:
text = (text-500)*.2
TotalCust_ovrtext = TotalCust_ovrtext + 1
elif text <=500:
text = 0
TotalBill = ((monthly_charge + data_plan + text + minute + data) * (tax)) + govfees
print ("Your Total Bill is... " + str(round(TotalBill,2)))
print "The toatal number of Customer's who went over their minute's usage limit is... " ,TotalCust_ovrminute
print "The total number of Customer's who went over their texting limit is... " ,TotalCust_ovrtext
print "The total number of Customer's who went over their data limit is... " ,TotalCust_ovrdata
Some of the variables created are not used in the program. Please overlook them.
As Preet suggested.
create another variable like TotalBill i.e.
AccumulatedBill = 0
Then at the end of your loop put.
AccumulatedBill += TotalBill
This will add each TotalBill to Accumulated. Then simply print out the result at the end.
print "Total for all customers is: %s" %(AccumulatedBill)
Note: you don't normally use uppercase on variables for the first letter of the word. Use either camelCase or underscore_separated.

How can you simulate a SQL join in C++ using STL and or Boost

How can you simulate a SQL join between two dynamic data sets ( i.e. data is obtained at runtime ) using c++.
Example Table A is a 2D vector of vectors ( any STL or Boost data structure is OK ) of students, their names and course numbers. Table B is a 2D vector of vectors ( any STL or Boost data structure is ok) of course number, description and room numbers
//Table A
// Columns: StudentID FirstName LastName CourseNum
std::vector<std::string> a1 = boost::assign::list_of("3490")( "Saundra")( "Bribiesca")( "F100X");
std::vector<std::string> a2 = boost::assign::list_of("1288")( "Guy")( "Shippy")( "F103X");
std::vector<std::string> a3 = boost::assign::list_of("5383")( "Tia")( "Roache")( "F103X");
std::vector<std::string> a4 = boost::assign::list_of("5746")( "Jamie")( "Grunden")( "F101X");
std::vector<std::string> a5 = boost::assign::list_of("2341")( "Emilia")( "Hankinson")( "F120X");
std::vector<std::vector<std::string > > TableA = boost::assign::list_of(a1)(a2)(a3)(a4)(a5);
//Table B
//Columns: CourseNum CourseDesc Room
std::vector<std::string> b1 = boost::assign::list_of("F100X")("Human Biology")("400B");
std::vector<std::string> b2 = boost::assign::list_of("F103X")("Biology and Society")("500B");
std::vector<std::string> b3 = boost::assign::list_of("F101X")("The Dynamic Earth 340A");
std::vector<std::string> b4 = boost::assign::list_of("F120X")("Glaciers, Earthquakes and Volcanoes")("300C");Earthquakes and Volcanoes");
std::vector<std::vector<std::string > > TableB = boost::assign::list_of(b1)(b2)(b3)(b4);
//Table C ( result of joining A and B ) using TableA[3] and TableB[0] as key
//I want to produce a resultset Table C, like this
Table C
StudentID FirstName LastName Room CourseNum CourseDesc
3490 Saundra Bribiesca 400B F100X Human Biology
1288 Guy Shippy 500B F103X Biology and Society
5383 Tia Roache 500B F103X Biology and Society
5746 Jamie Grunden 340A F101X The Dynamic Earth
2341 Emilia Hankinson 300C F120X Glaciers, Earthquakes and Volcanoes
SQL engines use various different techniques to perform joins, depending what indexes are available (or what hashtables it thinks should be created on the fly).
The simplest though is an O(N*M) nested loop over both tables. So to do an inner join you compare every pair of elements one from A and one from B. When you see a match, output a row.
If you need to speed things up, in this case you could create an "index" of table B on its first column, that is a std::multimap with the first column as the key, and a tuple[*] of the rest of the columns as value. Then for each row in A, look up its third column in the index and output one row per match. If the CourseNum is unique in table B, as seems sensible, then you can use a map rather than a multimap.
Either way gets you from O(N*M) to O((N+M)*logM), which is an improvement unless N (the size of table A) is very small. If your college has very many fewer students than courses, something is badly wrong ;-)
[*] where by "tuple" I mean anything that holds all the values - you've been using vectors, and that will do.
Since only answer doesn't have any code...
Please note that design (vector of strings instead of class makes code unreadable)
int main()
{
map<string,std::vector<vector<string > >::const_iterator> mapB;
for(auto it = TableB.cbegin(); it!=TableB.cend(); ++it)
{
mapB[(*it)[0]]=it;// in first map we put primary key and iterator to tableB where that key is
}
assert(mapB.size()== TableB.size());// how unique is primary key?
for_each(TableA.cbegin(), TableA.cend(),
[&mapB] (const vector<string>& entryA )
{
auto itB= mapB.find(entryA.at(3));
if (itB!=mapB.end()) // if we can make "JOIN" we do it
{
auto entryB = itB->second;
cout << entryA.at(0) << " " << entryA.at(1) << " " << entryA.at(2) << " " << entryB->at(2) << " " << entryB->at(0) << " " << entryB->at(1) << endl;
}
});
}
Output:
C:\STL\MinGW>g++ test.cpp &&a.exe
3490 Saundra Bribiesca 400B F100X Human Biology
1288 Guy Shippy 500B F103X Biology and Society
5383 Tia Roache 500B F103X Biology and Society
5746 Jamie Grunden 340A F101X The Dynamic Earth
2341 Emilia Hankinson 300C F120X Glaciers, Earthquakes and Volcanoes