Tell me whats wrong with this function? - function

def compute_invigilated_mark():
"""Prints given name and family name with overall score"""
test = 0.15
exam = 0.60
first_name = input("Given names(s)? ")
last_name = input("Family name? ")
both_names = last_name.upper() + "," + first_name.title()
new_test_percent = float(input("Test percent? ")) * test
new_exam_percent = float(input("Exam percent? ")) * exam
overall_percent = new_test_percent + new_exam_percent
end_result = overall_percent / (exam + test)
print(both_names + end_result)
compute_invigilated_mark()
I want to get the end result of, For example: Bourne, Jason: 66.0
The rrror message:
builtins.TypeError: Can't convert 'float' object to str implicitly.
NB: I spaced it out like this so you could read it easier :).

both_names is a string and end_result is a float, yet you are trying to add\concat them together (print(both_names + end_result)).
You should convert end_result to a string:
print(both_names + str(end_result))

Related

Pulling data in a for loop where data sometimes does not exist

Let's say I have four data values and one of them exists sometimes.
My For loop crashes because the path doesn't exist.
I would like to pass a "" in the cell instead of crashing.
myJSON.data[i].bank[0].money <- this part is my problem, because the bank[0].money sometimes doesn't exist.
I would like to keep the cell empty.
I tried an If but I didn't get it formatted properly, same goes for error handling.
Sub DATA()
Set RDict = CreateObject("Scripting.Dictionary")
Set dlist = CreateObject("Scripting.Dictionary")
JSON_String = Form.fromURL("exampleurl")
With CreateObject("htmlfile")
With .parentWindow
.execScript "var myJSON = " & JSON_String & ", csvstring = '';for (i = 0; i < myJSON.data.length; i++) {csvstring += myJSON.data[i].name + ',' + myJSON.data[i].bank[0].money + ',' + myJSON.data[i].location + ',' + myJSON.data[i].planneddate + ';';};"
RData = Split(.csvstring, ";")
End With
End With
For i = 0 To UBound(RData) - 1
DaData = Split(RData(i), ",")
If DaData(0) <> "null" Then RDict(DaData(0)) = DaData
Next i
Dim RSheet() As Variant
If RDict.Count > 0 Then
ReDim RSheet(2 To RDict.Count + 2, 1 To 7)
i = 0
For Each D In RDict
datalist(RDict(Da)(2)) = True
For j = 0 To 6
RSheet(i + 2, j + 1) = RDict(Da)(j)
Next j
i = i + 1
Next Da
RSData.Cells(2, 1).Resize(i, 6) = RSheet
End If
End Sub
You can handle null by using optional chaining with default nullish coalescing (#3 in example).
Something like this should work
Change myJSON.data[i]?.bank[0]?.money
To myJSON.data[i]?.bank[0]?.money ?? 'Unknown'
You can do the same with your other variables (myJSON.data[i].location and myJSON.data[i].planneddate) if they have the potential to be undefined or null as well
EDIT - Use Optional IF when optional chaining is not available
If that feature is not available in HTMLDocument's javascript maybe you can use basic conditional if?
This should work for undefined object, because undefined is == null
(myJSON.data[i].bank[0].money != null ? myJSON.data[i].bank[0].money : '-')

i want to sum three fields which is get through database

page.ts
price = 300,residential_package = 120, accompany = 1335;
this.delegates_total = this.price + this.residential_package + this.accompany;
result shows 3001201335
I want to add these fields value but it doesn't give me correct result please tell me where m going wrong and thank you for your help
use Number() to convert to number and then use +;
Or you can use + to convert to number like +this.price;
price = 300,residential_package = 120, accompany = 1335;
this.delegates_total = Number(this.price) + Number(this.residential_package) + Number(this.accompany);
in your case you are concatenate 3 strings
declare your fields with type
price:number=300
residential_package:number=120
accompany:number=1335

Query Large Data from Fusion Tables from Google Apps Script

I've loaded a 66 MB csv file to Fusion Tables. It's about 475k rows long and 12 columns wide.
I'm using Google Apps Script and trying to query the data within there.
One of the columns is the name of the person who that data belongs to, for instance, Joe.
If I want to pull all of Joe's data out so I can display it to him in a nice format, I'm using this query:
var tableId = my_table_id;
var sql1 = "SELECT * FROM " + tableId + " WHERE 'User' = 'Joe'";
var result = FusionTables.Query.sql(sql1,{hdrs : false});
The issue is that Joe has about 52k lines of data. I want to return it so I can load it to a datable and the user can sort through it and view all of the data. I get one of two errors:
If I run the query as above I get:
Response Code: 413. Message: response too large.
If I just try to select it all (SELECT * FROM tableId), I get:
Response size is larger than 10 MB. Please use media download
For media download, I've tried specifying alt : 'media' in the parameters, but I don't think that works within Google Apps script (I can't find documentation on it anywhere).
I have also tried looping through the queries, so select * limit 0,1000, then select * limit 1001,2000, ect. However, fusion tables SQL doesn't seem to support that either.
At this point, I may just leave the CSV in my drive, parse it in on the fly, but that's my last resort. Any advice would be appreciated!
So I think I figured this out. I'm sure it's not the most elegant solution, but here goes:
I run a quick query to check the count() for Joe to see how many records there are and only run loops if needed. I set the max to 40,000 records:
var total_rows_query = "SELECT COUNT() FROM " + tableId + " WHERE 'User' = " + username;
var total_rows = FusionTables.Query.sql(total_rows_query,{hdrs : false}).rows[0][0];
If the total rows are greater than I want, I use the OFFSET and LIMIT parameters to structure the queries:
max_rows = 40000;
if(total_rows > max_rows){
var counter = 0;
//adding in a zero to the ranges since the last query will be the offset of 0, meaning all of them
var ranges = [0]
while(counter + chunk_size < total_rows){
counter = counter + chunk_size;
ranges.push(counter)
}
ranges.push(total_rows)
//Now ranges is an array with zero at the beginning, and counting up by the chunk size I want, ending with the total_rows for the user as the last oen
//This is the array that will be output after concating
var output = []
//looping through the array, setting the offset to the first item, and the limit to the next item minus the first
for(i=0;i<ranges.length-1;i++){
var offset = ranges[i]
var limit = ranges[i+1] - offset
var query = "SELECT * FROM " + tableId + " WHERE 'User' = '" + username + "' OFFSET " + offset + " LIMIT " + limit;
output = output.concat(FusionTables.Query.sql(query,{hdrs : false}).rows)
}
}else{
//if the count is less or equal to the chunk size, just run the one query
var query = "SELECT * FROM " + tableId + " WHERE 'User' = " + username;
var output = FusionTables.Query.sql(query,{hdrs : false}).rows
}
The last thing to note is that if the username is two words, for instance 'John Smith', you may need to add in quotes around your username, so instead of
var total_rows_query = "SELECT COUNT() FROM " + tableId + " WHERE 'User' = " + username;
It would be:
var total_rows_query = "SELECT COUNT() FROM " + tableId + " WHERE 'User' = '" + username + "'";
I spend the last two days trying to figure this out, so I hope it helps someone out there!

Variables as field names

For R = 1 To NRrows
If (RSNonResourceCosts![CostType]) <> "" Then
CL(1) = CL(1) + 1
WKS.Cells(199 + R, 1) = (RSNonResourceCosts![CostType])
End If
If (RSNonResourceCosts![SoftwareCosts]) <> "" Then
CL(2) = CL(2) + 1
WKS.Cells(199 + R, 2) = (RSNonResourceCosts![SoftwareCosts])
End If
RSNonResourceCosts.MoveNext
Next R
Attached is a "Cut down" version of the code. I am writing to an Excel spreadsheet to apply Indirect formula. [CostType] and [SoftwareCosts] in the example are constants at the moment.
I want the user to be able to add fields without then having to amend the code. The new field name will be derived from the table. Is it possible to use a field name (not known until the table is modified) between the square brackets?
Yes:
FieldName = "SomeField"
WKS.Cells(199 + R, 1) = RSNonResourceCosts.Fields(FieldName).Value

creating mysql table from dymanic list python

I have a list of strings that change dynamically. I need to create a MySQL table where each string in the list is a name of a column.Note: I have found some examples using sqlalchemy but it didn't help me at all.
here is my try:
f = open(filepath,"r")
pluginoutput= f.read()
pluginoptojson = json.loads(pluginoutput)
columnsnames = (pluginoptojson["columns"])
countcolumns = len(pluginoptojson["columns"])
count = 0
lst = []
for name in columnsnames:
if count < countcolumns:
lst.append(str(name))
count +=1
lst.append("caseid")
createsqltable = """CREATE TABLE IF NOT EXISTS %s""" + for t in columnsnames: """ """ (test)
c.execute(createsqltable)
conn.commit()
c.close()
conn.close()
my head is about to explode of thinking. any help will be appreciated.
first thanks alot to Irnzcig.
I just tested his recommendation and it worked like charm. the code is:
pluginoutput= f.read()
pluginoptojson = json.loads(pluginoutput)
columnsnames = (pluginoptojson["columns"])
countcolumns = len(pluginoptojson["columns"])
count = 0
lst = []
for name in columnsnames:
if count < countcolumns:
lst.append(str(name))
count +=1
lst.append("caseid")
table_name = "test1"
createsqltable = """CREATE TABLE IF NOT EXISTS """ + table_name + " (" + " VARCHAR(50),".join(lst) + " VARCHAR(50))"
c.execute(createsqltable)
conn.commit()
c.close()
conn.close()
gc.collect()