Google apps script - If function logic & URL - if-statement

How can I add the "radiobutton" so that it is after the if statement - when I originally tried to do it - it created two forms?
Also how can I capture the URL of the form that is created so that I can send it to the approver of the sheet in MailApp.sendEmail?
if (period == 'Yes'){
var form = FormApp.create("Request for Leave" + UID)
.setTitle(name + " REQUEST FOR LEAVE" )
.setDescription("LEAVE DATES REQUESTED; \n\n" + date_from + " to " + date_to + "\n\nTYPE OF LEAVE; \n\n" + paid + " " + leave_type + "\n\nREASON FOR THE REQUEST; \n\n " + info + "\n\nCOVER HAS BEEN ARRANGED BY \n\n" + cover +"\n" );
// radiobuttons
item = "Leave approved?";
var choices = ["YES", "NO",];
form.addMultipleChoiceItem()
.setTitle(item)
.setChoiceValues(choices)
.setRequired(true);
}
/**Following is for part of day */
{ var form = FormApp.create("Request for Leave" + UID)
.setTitle(name + " PARTIAL DAY REQUEST FOR LEAVE" )
.setDescription("LEAVE DATE REQUESTED; \n\n" + date_from + " between " + time_from + " and " + time_to + "\n\nTYPE OF LEAVE; \n\n" + paid + " " + leave_type + "\n\nREASON FOR THE REQUEST; \n\n " + info + "\n\nCOVER HAS BEEN ARRANGED BY \n\n" + cover +"\n" );
// radiobuttons
item = "Leave approved?";
var choices = ["YES", "NO",];
form.addMultipleChoiceItem()
.setTitle(item)
.setChoiceValues(choices)
.setRequired(true);

Related

can't add everything together? (stuck on the last code)

*ignore this part, just look at the last few codes. im trying to add all the quanties together but the last code prints every purchase individually? How can i get it to print "Your purchases is" and add the quanties times their price all in one line instead of printing it for every individual
print "Enter a fruit name (or done):",
fruit = raw_input()
fruit_list = []
while fruit != "done":
fruit_list = fruit_list + [fruit]
print "Enter a fruit name (or done):",
fruit = raw_input()
price_list = []
for x in range(0, len(fruit_list)):
print "Enter the price for " + fruit_list[x] + ":",
price = float(raw_input())
price_list = price_list + [price]
# print " Your fruit list is:" + str(fruit_list)
# print "Your price list is:" + str(price_list)
print fruit_list
print price_list
quanity_list = []
for x in range(0, len(fruit_list)):
print str(fruit_list[x]) + str(price_list[x]) + " Quantity:",
quantity = int(raw_input())
print "Your total purchase is:", + price_list[x] * quantity
Try the following code :
Replace your last part of code with;
total = 0
quanity_list = []
for x in range(0, len(fruit_list)):
print str(fruit_list[x]) + str(price_list[x]) + " Quantity:",
quantity = int(raw_input())
total = total + price_list[x] * quantity
print "Your total purchase is:" + total

"Unboundlocalerror: Local Variable "Val" Referenced before Assignment" Error

I have been trying to get my script to loop in such a way that it will load the outputs in 1 file, and then when it's done loading everything move the values to output file 2 , erase the values in output file 1 and start reloading them, then when those are down move the values into output two (overwriting the old ones) repeat.
I have been pretty successful so far and don't know what else to add to my script and am hoping someone here knows why I keep getting ""Unboundlocalerror: Local Variable "Val" Referenced before Assignment" error randomly midway through the loading process, when I have a very small input file, the script performs how I want.
Does anyone know how I can change my script to fix that error, I have tried to understand why it is happening but cannot.
I have tried to research it thoroughly but none of the suggestions I have found have worked (or I implemented them incorrectly, I have attached my script. Thanks!
import urllib2,re,urllib,urlparse,csv,sys,time,threading,codecs,shutil
from bs4 import BeautifulSoup
def extract(url):
try:
sys.stdout.write('0')
# global file
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page, 'html.parser')
product = soup.find("div", {"class": "js-product-price"})
price = product.findNext('div',{'class': 'js-price-display'}).getText().strip()
oos = product.findNext('p', attrs={'class': "price-oos"})
if oos is None:
oos = 'In Stock'
else:
oos = oos.getText()
val = url + "," + price + "," + oos + "," + time.ctime() + '\n'
# ifile.write(val)
sys.stdout.write('1')
except Exception as e:
print e
return val
while True:
ifile = open('output.csv', "w", 0)
inputs = csv.reader(open('input.csv'))
# inputs = csv.reader(codecs.open('input.csv', 'rU', 'utf-16'))
ifile.write('URL' + "," + 'Price' + "," + 'Stock' + "," + "Time" + '\n')
for i in inputs:
ifile.write(extract(i[0]))
ifile.close()
Update:
Thanks for the help guys! This is my new script:
import urllib2,re,urllib,urlparse,csv,sys,time,threading,codecs,shutil
from bs4 import BeautifulSoup
def extract(url):
try:
sys.stdout.write('0')
# global file
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page, 'html.parser')
product = soup.find("div", {"class": "js-product-price"})
price = product.findNext('div',{'class': 'js-price-display'}).getText().strip()
oos = product.findNext('p', attrs={'class': "price-oos"})
if oos is None:
oos = 'In Stock'
else:
oos = oos.getText()
val = url + "," + price + "," + oos + "," + time.ctime() + '\n'
# ifile.write(val)
sys.stdout.write('1')
except Exception as e:
print e
else:
return val
while True:
ifile = open('output.csv', "w", 0)
inputs = csv.reader(open('input.csv'))
# inputs = csv.reader(codecs.open('input.csv', 'rU', 'utf-16'))
ifile.write('URL' + "," + 'Price' + "," + 'Stock' + "," + "Time" + '\n')
for i in inputs:
val_to_write = extract(i[0])
if val_to_write:
ifile.write(val_to_write)
ifile.close()
shutil.copy('output.csv', 'output2.csv')
print("finished")
With the above script I am now getting the error: "ValueError: I/O operation on closed file". Thanks
Use try-except-else as you would only want to return val if no exception was raised (if an exception was raised then val wouldn't be assigned to when you try to return it). Another suggestion is not to use a "catch-em-all" except block.
def extract(url):
try:
sys.stdout.write('0')
# global file
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page, 'html.parser')
product = soup.find("div", {"class": "js-product-price"})
price = product.findNext('div',{'class': 'js-price-display'}).getText().strip()
oos = product.findNext('p', attrs={'class': "price-oos"})
if oos is None:
oos = 'In Stock'
else:
oos = oos.getText()
val = url + "," + price + "," + oos + "," + time.ctime() + '\n'
# ifile.write(val)
sys.stdout.write('1')
except Exception as e:
print e
else:
return val
But be warned: if an exception does occur then extract will return None and the calling code will have to take account for that, for example:
for i in inputs:
val_to_write = extract(i[0])
if val_to_write:
ifile.write(val_to_write)
ifile.close()

I keep getting this error: type error: int object not iterable error when i try to run this. i dont seem to understand why

def calculate_tax(income_input):
income_inpu = {}
for item in income_input:
tax = '0'
income = income_input[item]
if income in range(0, 1001):
tax = (0*income)
if income in range(1001, 10001):
tax = (0.1 * (income-1000))
if income in range(10001, 20201):
tax = ((0.1*(10000-1000)) + (0.15*(income-10000)))
if income in range(20201, 30751):
tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200)))
if income in range(30751, 50001):
tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750)))
if (income > 50000):
tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000)))
income_inpu[item] = tax
return income_inpu

Python 2.7; How to clear an entry in the GUI

I have an example code, here just for BMI index. I would like to clear the input and output fields in the GUI. It seems that i can clear the entries, but the BMI calculation is not being removed (row 79 does not seem to have an effect) (# self.text.delete(0, 'end'))
Thanks
Emin
import math
from Tkinter import *
class Application(Frame):
"""A GUI application with three buttons"""
def __init__(self, master):
"""Initialize the Frame"""
Frame.__init__(self,master)
self.grid()
self.create_widgets()
self.title = Label(self, text = "BMI index calculation")
self.title.grid(row = 0, column = 0, columnspan = 2 , sticky =W)
def create_widgets(self):
"""Create button, text and entry widgets"""
self.name = Label(self, text = "What is your name?")
self.name.grid(row = 1, column = 0, columnspan = 2 , sticky =W)
self.name_io = Entry(self)
self.name_io.grid(row = 1, column =2, sticky = W)
self.age = Label(self, text = "How old are you?")
self.age.grid(row = 2, column = 0, columnspan = 2 , sticky =W)
self.age_io = Entry(self)
self.age_io.grid(row = 2, column =2, sticky = W)
self.height = Label(self, text = "How tall are you?")
self.height.grid(row = 3, column = 0, columnspan = 2 , sticky =W)
self.height_io = Entry(self)
self.height_io.grid(row = 3, column =2, sticky = W)
self.weight = Label(self, text = "How much do you weigh in kg?")
self.weight.grid(row = 4, column = 0, columnspan = 2 , sticky =W)
self.weight_io = Entry(self)
self.weight_io.grid(row = 4, column =2, sticky = W)
self.submit_button = Button(self, text = "Calculate", command = self.reveal)
self.submit_button.grid(row = 5, column = 0, sticky = W)
self.text = Text(self, width = 40, height = 5, wrap = WORD)
self.text.grid(row = 6, column = 0, columnspan = 3, sticky = W)
self.clear_button = Button(self, text = "Clear", command = self.clear_text)
self.clear_button.grid(row = 7, column = 0, sticky = W)
def reveal(self):
"""Display message based on the password typed in"""
content_name = self.name_io.get()
content_age = float(self.age_io.get())
content_height = float(self.height_io.get())
content_weight = float(self.weight_io.get())
BMI = round((content_weight/(content_height/100)**2.),1)
underBMI = 18.5
NormalBMI = 24.9
OverweightBMI = 29.9
ObesityBMI = 30
if BMI <= underBMI:
message = content_name + ", " + "your BMI index is" + " " + str(BMI) + ", " + "you are underweight, so you need to eat!"
elif (BMI > underBMI) and (BMI <= NormalBMI):
message = content_name + ", " + "your BMI index is" + " " + str(BMI) + ", " + "your BMI is Normal"
elif (BMI > NormalBMI) and (BMI <= OverweightBMI):
message = content_name + ", " + "your BMI index is" + " " + str(BMI) + ", " + "you are Overweight - need to exercise!"
elif (BMI > OverweightBMI):
message = content_name + ", " + "your BMI index is" + " " + str(BMI) + ", " + "you are in Obesity"
self.text.insert(0.0, message)
def clear_text(self):
self.name_io.delete(0, 'end')
self.age_io.delete(0, 'end')
self.height_io.delete(0, 'end')
self.weight_io.delete(0, 'end')
# self.text.delete(0, 'end')
root = Tk()
root.title("BMI Index")
root.geometry("600x350")
app = Application(root)
root.mainloop ()
The problem is that you're giving an index that is 0.0. Text widget indexes are a string of the form line.column but you're giving it a floating point number.
The proper index for the first character is the string "1.0".
self.text.delete("1.0", 'end')
Simply
your_entry.delete(0,END)

Partner Ledger Report using ORM methods in Odoo8

I am working on partner ledger report and i have prepared report using SQL query
def lines(self, partner):
move_state = ['draft','posted']
if self.target_move == 'posted':
move_state = ['posted']
full_account = []
if self.reconcil:
RECONCILE_TAG = " "
else:
RECONCILE_TAG = "AND l.reconcile_id IS NULL"
self.cr.execute(
"SELECT l.id, l.date, j.code, acc.code as a_code, acc.name as a_name,inv.state,inv.date_due, l.ref, m.name as move_name, l.name, l.debit, l.credit, l.amount_currency,l.currency_id, c.symbol AS currency_code " \
"FROM account_move_line l " \
"LEFT JOIN account_journal j " \
"ON (l.journal_id = j.id) " \
"LEFT JOIN account_account acc " \
"ON (l.account_id = acc.id) " \
"LEFT JOIN res_currency c ON (l.currency_id=c.id)" \
"LEFT JOIN account_move m ON (m.id=l.move_id)" \
"LEFT JOIN account_invoice inv ON (inv.move_id = l.move_id)" \
"WHERE l.partner_id = %s " \
"AND l.account_id IN %s AND " + self.query +" " \
"AND m.state IN %s " \
" " + RECONCILE_TAG + " "\
"ORDER BY l.date",
(partner.id, tuple(self.account_ids), tuple(move_state)))
res = self.cr.dictfetchall()
sum = 0.0
if self.initial_balance:
sum = self.init_bal_sum
for r in res:
sum += r['debit'] - r['credit']
r['progress'] = sum
full_account.append(r)
return full_account
My result are accurate
but now I want to do this using ORM methods and code for this:
account_move_model = self.pool.get('account.move.line')
full_account_custom = []
move_line_ids = account_move_model.search(self.cr, self.uid, [
('partner_id', '=', partner.id), ('account_id', 'in', tuple(self.account_ids)),
('state', 'in', tuple(move_state))
])
move_lines = account_move_model.browse(self.cr, self.uid, move_line_ids)
sum = 0.0
if self.initial_balance:
sum = self.init_bal_sum
for r in move_lines:
sum += r['debit'] - r['credit']
r['progress'] = sum
full_account_custom.append(r)
return full_account_custom
By doing this I am just getting the sum of all invoices of a partner/customer but the list of all invoice is not showing.
Where is the mistake and how to resolve it
Using ORM methods there are some difficulties..
Easy way is to use raw query.