if elif(conditions) in Jython FDMEE keeps giving wrong result - jython

it shall be a simple if elif(conditions) in jython, but it seems like Jython in FDMEE keeps checking for wrong result in the condition.
def Timetest(strField, strRecord):
import java.util.Date as date
import java.text.SimpleDateFormat as Sdf
import java.lang.Exception as Ex
import java.sql as sql
import java.util.concurrent.TimeUnit as TimeUnit
PerKey = fdmContext["PERIODKEY"]
strDate = strRecord.split(",")[11]
#get maturity date
strMM = strDate.split("/")[0]
strDD = strDate.split("/")[1]
strYYYY = strDate.split("/")[2]
strDate = ("%s.%s.%s" % (strMM,strDD, strYYYY))
#converting Maturity date
sdf = Sdf("MM.dd.yyyy")
strMRD = sdf.parse(strDate)
#calc date diff
diff = (strMRD.getTime()- PerKey.getTime())/86400000
diff = ("%d" % diff)
if diff>="0":
if diff <= "30":
return "Mat_Up1m " + diff
elif diff <= "90":
return "Mat_1to3m " + diff #the result goes here all the time although my diff is 367
elif diff <= "360":
return "Mat_3to12m " + diff
elif diff <= "1800":
return "Mat_1to5y " + diff #the result supposed to go here
else:
return "Mat_Over5y "+ diff
Not sure why it keeps going to the second elif instead of the fourth elif.
My calculation result of diff = 367
any idea on how to make sure that my code read the correct if elif condition?

Hope you have already figured it out, If not then check the mistakes you have made in your script.
In your script you're comparing string "367" with string values "0","90" etc., its not integer comparison, string "367" is always less than string "90" so its going into that elif condition.
Now you have to do integer comparison instead of string comparison and also move your all elif conditions inside the main if condition.
In the return statement you have to convert the interger to string to concatinate diff to a string.
Check the following code, with all the changes.
if diff>=0:
if diff <= 30:
return "Mat_Up1m " + str(diff)
elif diff <= 90:
return "Mat_1to3m " + str(diff)
elif diff <= 360:
return "Mat_3to12m " + str(diff)
elif diff <= 1800:
return "Mat_1to5y " + str(diff)
else:
return "Mat_Over5y "+ str(diff)

Related

What is the exit code -1073740791 (0xC0000409)?

def yetkiligoruntule(self):
self.ui.tableWidgetYetkilileriGoster.setRowCount(0)
query = "SELECT yetkili_id, yetkili_ad, yetkili_soyad, yetkili_num, yetkili_mail, yetkili_poz FROM yetkili"
result = cur.execute(query,).fetchall()
for row in result:
rowNumber = self.ui.tableWidgetYetkilileriGoster.rowCount()
self.ui.tableWidgetYetkilileriGoster.insertRow(rowNumber)
for columnNumber, data in enumerate(row):
self.ui.tableWidgetYetkilileriGoster.setItem(rowNumber, columnNumber, QTableWidgetItem(str(data)))
def yetkiliAra(self):
value = self.ui.lineEditYetkiliAra.text()
if value == "":
QMessageBox.warning(self,"Uyari","Lutfen yetkili adi giriniz!")
self.ui.lineEditYetkiliAra.setText("")
else:
query = "SELECT yetkili_id, yetkili_ad, yetkili_soyad, yetkili_num, yetkili_mail, yetkili_poz FROM yetkili WHERE yetkili_ad LİKE? or yetkili_soyad LİKE?"
result = cur.execute(query,('%' + value + '%','%' + value + '%'))
if result == []:
QMessageBox.warning(self,"Uyari","Kullanici Bulunamadi!")
self.ui.lineEditYetkiliAra.setText("")
return
else:
**self.ui.tableWidgetYetkilileriGoster.setRowCount(0)**
for row in result:
rowNumber = self.ui.tableWidgetYetkilileriGoster.rowCount()
self.ui.tableWidgetYetkilileriGoster.insertRow(rowNumber)
for columnNumber, data in enumerate(row):
self.ui.tableWidgetYetkilileriGoster.setItem(rowNumber, columnNumber, QTableWidgetItem(str(data)))
I think this line (which is bold) is the exact problem. Bu don't know how to solve it. Is there someone for help?
Just try ask here. I try to 'setRowCount()' like this without 0 but it doesn't work.

How to calculate all aggregations at once without using a loop over indices?

How to calculate all aggregations at once without using a loop over indices?
%%time
import random
random.seed(1)
df = pd.DataFrame({'val':random.sample(range(10), 10)})
for j in range(10):
for i in df.index:
df.loc[i,'mean_last_{}'.format(j)] = df.loc[(df.index < i) & (df.index >= i - j),'val'].mean()
df.loc[i,'std_last_{}'.format(j)] = df.loc[(df.index < i) & (df.index >= i - j),'val'].std()
df.loc[i,'max_last_{}'.format(j)] = df.loc[(df.index < i) & (df.index >= i - j),'val'].max()
df.loc[i,'min_last_{}'.format(j)] = df.loc[(df.index < i) & (df.index >= i - j),'val'].min()
df.loc[i,'median_last_{}'.format(j)] = df.loc[(df.index < i) & (df.index >= i - j),'val'].median()
You could use the rolling method, see for example:
df = pd.DataFrame({'val': np.random.random(100)})
for i in range(10):
agg = df["val"].rolling(i).aggregate(['mean', 'median'])
df[[f"mean_{i}", f"median_{i}"]] = agg.values
I think what you're looking for is something like this:
import random
random.seed(1)
df = pd.DataFrame({'val':random.sample(range(10), 10)})
for j in range(1, 10):
df[f'mean_last_{j}'] = df['val'].rolling(j, min_periods=1).mean()
df[f'std_last_{j}'] = df['val'].rolling(j, min_periods=1).std()
df[f'max_last_{j}'] = df['val'].rolling(j, min_periods=1).max()
df[f'min_last_{j}'] = df['val'].rolling(j, min_periods=1).min()
df[f'median_last_{j}'] = df['val'].rolling(j, min_periods=1).median()
However, my code is "off-by-one" relative to your example code. Do you intend for each aggregation INCLUDE value from the current row, or should it only use the previous j rows, without the current one? My code includes the current row, but yours does not. Your code results in NaN values for the first group of aggregations.
Edit: The answer from #Carlos uses rolling(j).aggregate() to specify list of aggregations in one line. Here's what that looks like:
import random
random.seed(1)
df = pd.DataFrame({'val':random.sample(range(10), 10)})
aggs = ['mean', 'std', 'max', 'min', 'median']
for j in range(10):
stats = df["val"].rolling(j, min_periods=min(j, 1)).aggregate(aggs)
df[[f"{a}_last_{j}" for a in aggs]] = stats.values

How to apply regular function to df third column?

I have df that currently has two columns df[['sys1','dia1']]
I created this function (the parameters are d= df['dia1'] and s = df['sys1'] :
Now i am trying to create a third column by using this function. It would look like this:
df['FirstVisitStge'] = df['FirstVisitStge'].apply(classify)
I am getting an error. I even tried using predefined parameters in the function and still getting an error. What am i doing wrong?
def classify(d,s):
if (d>=90 & d<100 & s<160) or (s >= 140 & s < 160 & d < 100):
return 'Stage 1'
elif (s >= 160 & s <180 & d <110) or (d >= 100 and d < 110 and s > 180):
return 'Stage 2'
elif s >= 180 or d >= 110:
return 'hypertensive crisis'
else:
return 'NA'

No method matching error when working with Vector{Int64]

I have the following code where firstly I add the values for each index from two columns and creating Vector{Int64}
df = CSV.read(joinpath("data", "data.csv"), DataFrame)
adding_columns = df.firstcolumn + df.secondcolumn
Then I will create a function as following:
function fnct(data::Vector{T}; var= 8) where { T <: Number }
V = []
for x in 1:size(data)[1]
strt = x-var
ending = x+var
avg = 0
if strt < 1
for y in 1:x+var
avg = avg+data[y]
end
avg = avg/(x+var-1)
elseif ending > size(data)[1]
for y in x-var:size(data)[1]
avg = avg+data[y]
end
avg = avg/(size(data)-x-var)
else
for y in x-var:x+var
avg = avg+data[y]
end
avg = avg/(2*var)
end
push!(V,avg)
end
return V
end
When trying:
typeof(adding_columns)
I will get:
Vector{Int64}
however when calling
fnct(adding_columns)
I will get:
ERROR: MethodError: no method matching -(::Tuple{Int64}, ::Int64)
I presume that it takes my adding_columns as Tuple but I do not get it why, when the typeof is giving me Vector.
How could I solve this problem?
size(data) is a tuple:
julia> size([1,2,3]::Vector{Int})
(3,)
...but you're subtracting an integer from it in avg = avg/(size(data)-x-var).
Did you mean avg = avg/(length(data)-x-var) or avg = avg/(size(data, 1)-x-var)?

SQL query in Ruby not finding DateTime in where statement properly

Appointments have two fields, an at (a datetime) and minutes (integer, length of appointment)
appointment_a: at = "2015-04-02 21:00:00", and minutes = 60, which already exists.
I'm trying to create appointment_b, where at = "2015-04-02 21:30:00", and minutes = 60.
This is a validation in the Appointment model:
def check_overlap
from = appointment_a.at
to = appointment_a.minutes * 60 + appointment_a.at
if Appointment.where('at >= ? AND at + minutes * 60 >= ?', from, to).emtpy? == false
errors.add(:at, (" field will cause overlap between existing appointments "))
end
end
Why is this not adding errors?
If you try to add a Time to an Integer you get an error:
Time can't be coerced into Fixnum
Maybe if you change your to variable declaration to this:
to = appointment_a.at + appointment_a.minutes * 60
This way, you're adding an Integer to a Time type, so there should be no errors