scope calling user-defined C# methods in #DECLARE statement - scope

Is it possible to use a user-defined C# method in a #DECLARE statement? I have some code like this, but it doesn't seem to work.
#DECLARE timespan int = 120;
#DECLARE endDate string = #"2022-03-09";
#DECLARE startDate string = GetStartDate(#endDate, #timespan);
...
#CS
public static string GetStartDate(string endDateString, int daysBefore)
{
TimeSpan timespan = new TimeSpan(daysBefore, 0, 0, 0);
DateTime endDate = DateTime.Parse(endDateString);
DateTime startDate = endDate - timespan;
var startDateString = startDate.ToString("u", CultureInfo.GetCultureInfo("en-US"));
startDateString = startDateString.Split(' ')[0];
return startDateString;
}
#ENDCS

Related

Instantiate tuple value in Cassandra UDA function with map and tuple value (for daily average)

I am trying to create a function which counts and sums values by day (to later calculate the average). I got this far:
CREATE OR REPLACE FUNCTION state_group_count_and_sum( state map<timestamp, frozen<tuple<bigint,double>>>, timestamp timestamp, value double )
CALLED ON NULL INPUT
RETURNS map<timestamp, frozen<tuple<bigint,double>>>
LANGUAGE java AS '
Date date = (Date) timestamp;
Calendar cal = Calendar.getInstance(); // locale-specific
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();
TupleValue tupleValue = state.get(date);
Long count = (Long) tupleValue.getLong(0);
if (count == null) count = 1L;
else count = count + 1L;
Double sum = (Double) tupleValue.getDouble(1);
if (sum == null) sum = value;
else sum = sum + value;
//if (tupleValue == null) ?
tupleValue.setLong(0, count);
tupleValue.setDouble(1, sum);
state.put(date, tupleValue);
return state; ' ;
CREATE OR REPLACE AGGREGATE group_count_and_sum(timestamp, double)
SFUNC state_group_count_and_sum
STYPE map<timestamp, frozen<tuple<bigint,double>>>
INITCOND {};
This fails because tupleValue is null at every new day which is not in the map yet. How do I instantiate a tuple value in a UDA?
Fixed it.
CREATE OR REPLACE FUNCTION state_group_count_and_sum( state map<timestamp, frozen<tuple<bigint,double>>>, timestamp timestamp, value double )
CALLED ON NULL INPUT
RETURNS map<timestamp, frozen<tuple<bigint,double>>>
LANGUAGE java AS '
Date date = (Date) timestamp;
Calendar cal = Calendar.getInstance(); // locale-specific
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();
TupleValue tupleValue = state.get(date);
if (tupleValue == null) {
com.datastax.driver.core.TupleType tupleType = com.datastax.driver.core.TupleType.of(com.datastax.driver.core.ProtocolVersion.NEWEST_SUPPORTED, com.datastax.driver.core.CodecRegistry.DEFAULT_INSTANCE, com.datastax.driver.core.DataType.bigint(), com.datastax.driver.core.DataType.cdouble());
tupleValue = tupleType.newValue(0L, 0.0);
}
Long count = (Long) tupleValue.getLong(0);
if (count == null) count = 1L;
else count = count + 1L;
Double sum = (Double) tupleValue.getDouble(1);
if (sum == null) sum = value;
else sum = sum + value;
tupleValue.setLong(0, count);
tupleValue.setDouble(1, sum);
state.put(date, tupleValue);
return state; ' ;
CREATE OR REPLACE AGGREGATE group_count_and_sum(timestamp, double)
SFUNC state_group_count_and_sum
STYPE map<timestamp, frozen<tuple<bigint,double>>>
INITCOND {};

Array of dates returns object System datetime not the actual value of the array

Question is I have a function call "GetDatesBetween" what this does is looks at my two datepickers leave_s_dp and leave_e_dp and gets the dates between them. I then want to turn this array into a string for use in my full_range text box, But it always returns System.DateTime[]. Any help would be greatly appreciated.
public:
List<DateTime> ^GetDatesBetween(DateTime startDate, DateTime endDate)
{
List<DateTime> ^allDates = gcnew List<DateTime>();
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
{
allDates->Add(date.Date);
}
return allDates;
}
private:
System::Void submit_button_Click(System::Object^ sender, System::EventArgs^ e) {
array<DateTime> ^dates = GetDatesBetween(leave_s_dp->Value.Date, leave_e_dp->Value.Date)->ToArray();
//array<DateTime> ^dates = GetDatesBetween(leave_s_dp->Value, leave_e_dp->Value)->ToArray();
String ^ days_between = dates->ToString();
full_range_text->Text = days_between;
}
You're calling ToString() on an array. That doesn't do what you expect it to. It's not clear exactly what you do expect it to do, but it's almost certainly not what you want.
You quite possibly want to call string.Join, e.g.
dates_between = String::Join(", ", dates);
That will just use the default date format though - which may not be what you want either.

Convert part of string to integer

I have two time values of type unicode and str like below:
time1 = "10:00 AM" #type: str
time2 = "10:15 AM" #type: unicode
I want to convert integer part of time1 and time2 i.e 10:00 and 10:15 to integer and check if time2 > time1.
Is there any way to convert part of string and unicode to integer ?
public static void main(String[] args) {
String s1 = "10:00 AM";
String s2 = "10:20 AM";
int s1_mins = toMinutes(toNumber(s1));
int s2_mins = toMinutes(toNumber(s2));
if(s1_mins < s2_mins){
System.out.println(s2 +" is more than "+ s1);
}else{
System.out.println(s1 +" is more than "+s2);
}
}
private static String toNumber(String s) {
String[] timeInNumber = s.split(" ");
return timeInNumber[0];
}
private static int toMinutes(String s) {
String[] hourMin = s.split(":");
int hour = Integer.parseInt(hourMin[0]);
int mins = Integer.parseInt(hourMin[1]);
int hoursInMins = hour * 60;
return hoursInMins + mins;
}
The above code helps you.
You should use datetime or time instead which provides an option to compare datetime objects:
from datetime import datetime
time_obj1 = datetime.strptime(time1, '%I:%M %p')
time_obj2 = datetime.strptime(time2, '%I:%M %p')
if time_obj1 > time_obj2:
...

How to subtract time in C#

I am taking two values from database as a string. Now I want to subtract these two values. Please help me and thanks in advance.
private void button3_Click_1(object sender, EventArgs e)
{
label4.Visible = true;
textBox3.Visible = true;
string condur = Properties.Settings.Default.DBConnectionString;
SqlConnection connection = new SqlConnection(condur);
string q1 = "select in_time from in_time where car_reg='" + comboBox1.Text + "' ";
string q2 = "select out_time from out_time where car_reg='" + comboBox1.Text + "' ";
SqlCommand command1 = new SqlCommand(q1, connection);
SqlCommand command2 = new SqlCommand(q2, connection);
try
{
connection.Open();
string q3=command1.ExecuteNonQuery().ToString();
string q4=command2.ExecuteNonQuery().ToString();
DateTime dt1 = DateTime.Parse(q3);
DateTime dt2 = DateTime.Parse(q4);
TimeSpan result = dt2 - dt1; ;
string result1 = result.ToString();
textBox3.Text = result1;
//MessageBox.Show("Insertion successful!");
//textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; comboBox1.Text = ""; comboBox3.Text = ""; textBox11.Text = ""; textBox6.Text = ""; textBox8.Text = ""; textBox9.Text = ""; richTextBox1.Text = ""; textBox4.Text="";
}
catch (Exception exp)
{
throw exp;
}
finally
{
connection.Close();
}
}
It looks like you answered your own question:
TimeSpan result = dt2 - dt1;
To subtract two DateTime values in C#, you simply use the subtraction operator. If there is something wrong with the code sample you posted, you should describe the error, and what you expected to happen.
Edit in response to comment
That exception has nothing to do with subtracting the dates, it has something to do with your conversion from the type string to the type DateTime. You are trying to parse from string to DateTime:
DateTime dt1 = DateTime.Parse(q3);
This fails because q3 does not represent a valid string. The reason why, is the way you (don't) query:
string q3=command1.ExecuteNonQuery().ToString();
ExecuteNonQuery does not return the results of the query, rather it returns the number of changed rows. In other words, ExecuteNonQuery is not intended for querying, but for update scenarios, etc.
What you probably want is to use ExecuteScalar, which returns a single value from the query. If the types in the DB are correct, it will come back as a DateTime, so you don't need to do the DateTime.Parse part. The relevant parts of your code would become:
DateTime q3 = (DateTime)command1.ExecuteScalar();
DateTime q4 = (DateTime)command2.ExecuteScalar();
TimeSpan result = q4-q3;
Oh, and BTW, please look up the terms "SQL Injection", and "parameterized queries" on Google.

How to format a Date variable in LWUIT?

I have an object whose class has a getter method , and this getter method returns a Date value. I want to show this value in a Label in the format DD/MM/YYYY.
How to achieve that with LWUIT ?
Thank you very much indeed
You can use this code to convert date to string format and pass the this string value to label.
public static String dateToString (long date)
{
Calendar c = Calendar.getInstance();
c.setTime(new Date(date));
int y = c.get(Calendar.YEAR);
int m = c.get(Calendar.MONTH) + 1;
int d = c.get(Calendar.DATE);
String t = (d<10? "0": "")+d+"/"+(m<10? "0": "")+m+"/"+(y<10? "0": "")+y;
return t;
}
To thank you here is a code of mine which formats a number :
public static String formatNombre(int trivialNombre, String separateur)
{
String pNombre, sNombreLeads, sNombre, argNombre, resultat;
int leadingBits;
int nbBit;
pNombre = String.valueOf(trivialNombre);
if (pNombre.length() > 3)
{
leadingBits = (pNombre.length())%3;
if (leadingBits != 0)
sNombreLeads = pNombre.substring(0, leadingBits).concat(separateur);
else
sNombreLeads = "";
nbBit = 0;
sNombre = "";
argNombre = pNombre.substring(leadingBits);
for (int i=0;i<argNombre.length();i++)
{
sNombre = sNombre.concat(String.valueOf(argNombre.charAt(i)));
nbBit++;
if (nbBit%3 == 0)
sNombre = sNombre.concat(separateur);
}
sNombre = sNombre.substring(0, sNombre.length() - 1);
resultat = sNombreLeads.concat(sNombre);
return resultat;
}
else
return pNombre;
}

Resources