Day(s) of week selection from QT checkbox to Postgresql - c++

I have a group of checkboxes representing the days of a week in my Qt application GUI and I select one or many days, and depending on which boxes are checked, pass a query string to PostgreSQL in order to display certain data on those days -e.g. if I checked monday and wednesday, extract (dow from timestamp) = 1 or extract(dow from timestamp) = 3 should be added to my query. I have just typed a crude solution -though haven't tested yet as I write this-, but I was wondering if there is a shorter -and more elegant- approach that I'm missing out here. The code is as below: -the queryAdditionCalltimePart and queryAdditionCallStampPart strings are later added to the relevant parts of my main query's QString before the main query is executed-
bool checkboxArray[7];
bool mult = false;
checkboxArray[0] = this->ui->checkBoxMonday->isChecked();
checkboxArray[1] = this->ui->checkBoxTuesday->isChecked();
checkboxArray[2] = this->ui->checkBoxWednesday->isChecked();
checkboxArray[3] = this->ui->checkBoxThursday->isChecked();
checkboxArray[4] = this->ui->checkBoxFriday->isChecked();
checkboxArray[5] = this->ui->checkBoxSaturday->isChecked();
checkboxArray[6] = this->ui->checkBoxSunday->isChecked();
QString queryAdditionCalltimePart = "";
QString queryAdditionCalStampPart = "";
int count = 0;
queryAdditionCalltimePart.append("(");
queryAdditionCalStampPart.append("(");
for(int i = 0; i < 7; i++)
{
if(checkboxArray[i] == true)
{
count++;
}
}
int x = 0;
for(int i = 0; i < 7; i++)
{
if(checkboxArray[i] == true)
{
queryAdditionCalltimePart.append("(SELECT EXTRACT(DOW FROM calltime) = '" +QString::number(i+1)+"')");
queryAdditionCalStampPart.append("(SELECT EXTRACT(DOW FROM cal.stamp) = '" +QString::number(i+1)+"')");
}
if(count > 1 && checkboxArray[i] == true)
{
if(x == count - 1)
{
}
else
{
queryAdditionCalltimePart.append("OR");
queryAdditionCalStampPart.append("OR");
x++;
}
}
}
queryAdditionCalltimePart.append(")");
queryAdditionCalStampPart.append(")");

You can add properties to any widget in Qt, http://qt-project.org/doc/qt-4.8/qobject.html#setProperty. The property can have any information that you want.
In your particular case, it would be cleaner to attach the SQL string as a property for each checkbox.
this->ui->checkBoxMonday->setProperty("sql",
"(SELECT EXTRACT(DOW FROM calltime) = '" +QString::number(i+1)+"') OR ";
Once you receive the user input, simply append the check box properties and remove the final OR.

Related

MariaDB Connector C, mysql_stmt_fetch_column() and memory corruption

I'm working on a wrapper for MariaDB Connector C. There is a typical situation when a developer doesn't know a length of a data stored in a field. As I figured out, one of the ways to obtain a real length of the field is to pass a buffer of lengths to mysql_stmt_bind_result and then to fetch each column by calling mysql_stmt_fetch_column. But I can't understand how the function mysql_stmt_fetch_column works because I'm getting a memory corruption and app abortion.
Here is how I'm trying to reach my goal
// preparations here
...
if (!mysql_stmt_execute(stmt))
{
int columnNum = mysql_stmt_field_count(stmt);
if (columnNum > 0)
{
MYSQL_RES* metadata = mysql_stmt_result_metadata(stmt);
MYSQL_FIELD* fields = mysql_fetch_fields(metadata);
MYSQL_BIND* result = new MYSQL_BIND[columnNum];
std::memset(result, 0, sizeof (MYSQL_BIND) * columnNum);
std::vector<unsigned long> lengths;
lengths.resize(columnNum);
for (int i = 0; i < columnNum; ++i)
result[i].length = &lengths[i];
if (!mysql_stmt_bind_result(stmt, result))
{
while (true)
{
int status = mysql_stmt_fetch(stmt);
if (status == 1)
{
m_lastError = mysql_stmt_error(stmt);
isOK = false;
break;
}
else if (status == MYSQL_NO_DATA)
{
isOK = true;
break;
}
for (int i = 0; i < columnNum; ++i)
{
my_bool isNull = true;
if (lengths.at(i) > 0)
{
result[i].buffer_type = fields[i].type;
result[i].is_null = &isNull;
result[i].buffer = malloc(lengths.at(i));
result[i].buffer_length = lengths.at(i);
mysql_stmt_fetch_column(stmt, result, i, 0);
if (!isNull)
{
// here I'm trying to read a result and I'm getting a valid result only from the first column
}
}
}
}
}
}
If I put an array to the mysql_stmt_fetch_column then I'm fetching the only first field valid, all other fields are garbage. If I put a single MYSQL_BIND structure to this function, then I'm getting an abortion of the app on approximately 74th field (funny thing that it's always this field). If I use another array of MYSQL_BIND then the situation is the same as the first case.
Please help me to understand how to use it correctly! Thanks
Minimal reproducible example

How to read in data from a json file until there is no more data to read in QT

Basically I am using an API to retrieve stock data to me in the form of a ytd so it will return data of the closing price of the stock everyday from january until now. At first I was simply using a for loop and reading until i < json.size() but after figuring out the .size() does not properly return what i need for it to work i am again stuck on this. My code is below
//Retrieves json format of data
Json::Value chartData = IEX::stocks::chartYtd(symbol_std);
//Stores x and y values
QVector<double> time(365), closePrice(365);
//Intialize first vector to first values
closePrice[0] = chartData[0]["close"].asDouble();
time[0] = startYearTime;
//Finds max and min for range
float maxAvg = closePrice[0];
float minAvg = closePrice[0];
//Reads in data from json(historical data 1 day delayed)
for(int i = 1; ; i++)
{
time[i] = startYearTime + 86400*i;
closePrice[i] = (chartData[i]["close"].asDouble());
if((closePrice[i] == 0) && (time[i] != chartData.size() - 1))
{
closePrice[i] = closePrice[i-1];
}
if(closePrice[i] > maxAvg)
{
maxAvg = closePrice[i];
}
else if(closePrice[i] < minAvg)
{
minAvg = closePrice[i];
}
}
The json file looks like this
what can i do to have my code store the "close" value in the json file until there is no more "close" value to read in and then in which it stops, thank you in advance as im a new developer!

Flutter List Value Being Unintentionally Updated

In the code below the print for 'Second Sel Food Date' food date should match 'Initial Sel Food Date', but they don't because 'tempSelected[i].set_eatenDateTime = copyToDate.millisecondsSinceEpoch;' is updating both lists. How can I prevent foodListSelected from being updated? The initial values for foodListSelected are being passed into the class using a stream provider, if that matters.
List<FoodModel> tempSelected = new List();
for (var i = 0; i < foodListSelected.length; i++) {
tempSelected.add(foodListSelected[i]);
}
for (var i = 0; i < tempSelected.length; i++) {
print('Initital Sel Food Date: ' + DateFormat('E-MM-yyyy hh:mm:ss').format(DateTime.fromMillisecondsSinceEpoch(foodListSelected[i].eatenDateTime)));
DateTime eatenDateTime = DateTime.fromMillisecondsSinceEpoch(tempSelected[i].eatenDateTime);
DateTime copyToDate = DateTime(picked.year, picked.month, picked.day, eatenDateTime.hour, eatenDateTime.minute, eatenDateTime.second);
// ISSUE!!!!!
// This is some how setting foodListSelected[i].eatenDateTime as well.
tempSelected[i].set_eatenDateTime = copyToDate.millisecondsSinceEpoch;
tempSelected[i].set_selected = false;
_createFood('eaten_food', tempSelected[i]);
}
}
for (var i = 0; i < foodListSelected.length; i++) {
print('Second Sel Food Date: ' + DateFormat('E-MM-yyyy hh:mm:ss').format(DateTime.fromMillisecondsSinceEpoch(foodListSelected[i].eatenDateTime)));
foodListSelected[i].set_selected = false;
_updateEatenFood(foodListSelected[i]);
}
You are calling a mutator method on the same object which exists in both lists. If you want to create a new object copy for the second list, you should write a method that clones the current object, and use that in your first loop.

Count of CheckBoxList items selected isn't being calculated correctly

I'm currently trying to get a count of a CheckBoxList to use in conjunction with an if and else statement for a project. If the count is not equal to 2 I have a label that prompts the user to select two modules but the count isn't being calculated properly. Any help would be appreciated. Here is the code in question:
protected void RegisterButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["UniString"].ConnectionString);
//This integer will hold the number of modules selected
Int32 amount = 0;
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
//amount will increment each time a module checkbox is checked
if (CheckBoxList1.Items[i].Selected)
{
amount = amount++;
}
//If amount is not equal to 2 the code below will run
if (amount != 2)
{
//If the number of modules selected is not equal to 2 then this message is displayed and the background of the label in the markup is turned red to draw attention
ModuleSelectionMessage.Text = "Please select 2 modules to successfully register";
ModuleSelectionMessage.BackColor = System.Drawing.Color.Red;
}
else
{...
amount = amount++ is not assign amount value properly,
use amount++ or amount= amount + 1 instead of that..
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
//amount will increment each time a module checkbox is checked
if (CheckBoxList1.Items[i].Selected)
{
amount = amount + 1;
}
//other code...
}

List of windows users remotely

I would like to know how to retrieve the list of users that are logged onto a Remote machine. I can do it with qwinsta /server:xxxx, but would like to do it in C#.
check out wmi in .net under system.management.
something like:
ConnectionOptions conn = new ConnectionOptions();
conn.Authority = "ntdlmdomain:NAMEOFDOMAIN";
conn.Username = "";
conn.Password = "";
ManagementScope ms = new ManagementScope(#"\\remotecomputer\root\cimv2", conn);
ms.Connect();
ObjectQuery qry = new ObjectQuery("select * from Win32_ComputerSystem");
ManagementObjectSearcher search = new ManagementObjectSearcher(ms, qry);
ManagementObjectCollection return = search.Get();
foreach (ManagementObject rec in return)
{
Console.WriteLine("Logged in user: " + rec["UserName"].ToString());
}
You may not need the ConnectionOptions...
I ended up using the qwinsta /server:server1 command from C# -- it was much easier
thanks Ken
All this checks all 8 servers at the same time -- I put the result in sql server
but you can do what ever you want
query_citrix.bat script
cd C:.......\bin\citrix_boxes
qwinsta -server:servername or ip > servername.txt
string sAppCitrixPath = Application.StartupPath.ToString() + "\\citrix_boxes\\";
//Run Script for current citrix boxes
Process proc = new Process();
ProcessStartInfo si = new ProcessStartInfo();
si.FileName = sAppCitrixPath + "query_citrix.bat";
proc.StartInfo = si;
proc.Start();
proc.WaitForExit();
int exitCode = proc.ExitCode;
proc.Close();
if (exitCode == 0)
{
//Execute update who is on the Citrix_Boxes Currently
DirectoryInfo dic = new DirectoryInfo(sAppCitrixPath);
FileInfo[] fic = dic.GetFiles("*.txt");
for (int i = 0; i < fic.Length; i++)
{
ParseQWinStaServerFile(fic[i].FullName.ToString(), fic[i].Name.ToString().ToUpper().Replace(".TXT",""));
File.Delete(fic[i].FullName.ToString());
}
}
private void ParseQWinStaServerFile(string sLocation,string sServer)
{
using (StreamReader sr = File.OpenText(sLocation))
{
string sRecord = String.Empty;
char[] cSep = new char[] {' '};
bool bFirst = true;
while ((sRecord = sr.ReadLine()) != null)
{
if (bFirst == false)
{
string[] items = sRecord.Split(cSep, StringSplitOptions.RemoveEmptyEntries);
//Make sure all columns are present on the split for valid records
if (sRecord.Substring(19, 1) != " ") // check position of user id to see if it's their
{
//Send the user id and server name where you want to.
//here is your user
id = items[1].ToString().ToLower().Trim()
//here is your server
};
}
else
{
bFirst = false;
}
}
}
}