Trouble with break statement in While loop - while-loop

I'm trying to write a program that collects information from the user, then outputs to a text file. The program collects input correctly, as the print statement I inserted tells me, but the break statement doesn't break the loop when the specified value is input, and the output file is never updated. Any suggestions you could give would really help. Thanks!
# 1. Define Greeting:
def greeting():
print("Welcome, user! Please enter the address data, or type 'quit'.")
# 2. Input
def inputData():
name = input("Enter the name: ")
address = input("Enter the address: ")
city = input("Enter the city: ")
state = input("Enter the state: ")
zipCode = input("Enter the zip: ")
phone = input("Enter the phone number: ")
addressData = str(name + ", " + address + ", " +
city + ", " + state + ", "+ zipCode +
", " + phone)
print(addressData)
return(name)
# 3. Write data to text file
def dataWrite():
f.write(addressData + "\n")
# 4. Display the goodbye message:
def goodbye():
print("Have a nice day!")
# 5. Define Main function:
def main():
greeting()
while name != "quit":
inputData()
if name == "quit":
break
else:
dataWrite()
f.close()
goodbye()
main()

def main():
greeting()
while name != "quit":
name = inputData()
if name == "quit":
break
else:
dataWrite()
f.close()
goodbye()
You are not getting the return value of inputData().

Related

My input function and len function does not return a correct result in some cases

I have a question I wrote this script to format an arabic text to a certain format. But I found a problem then when I type a longer sentence it adds more dots then there are letters. I will paste the code here and explain what the problem is.
import itertools
while True:
input_cloze_deletion = input("\nEnter: text pr 'exit'\n> ")
input_exit_check = input_cloze_deletion.strip().lower()
if input_exit_check == "exit":
break
# copy paste
interpunction_list = ["الله", ",", ".", ":", "?", "!", "'"]
# copy paste
interpunction_list = [ ",", ".", ":", "?", "!", "'", "-", "(", ")", "/", "الله", "اللّٰـه"]
text_replace_0 = input_cloze_deletion.replace(",", " ,")
text_replace_1 = text_replace_0.replace(".", " .")
text_replace_2 = text_replace_1.replace(":", " :")
text_replace_3 = text_replace_2.replace(";", " ;")
text_replace_4 = text_replace_3.replace("?", " ?")
text_replace_5 = text_replace_4.replace("!", " !")
text_replace_6 = text_replace_5.replace("'", " ' ")
text_replace_7 = text_replace_6.replace("-", " - ")
text_replace_8 = text_replace_7.replace("(", " ( ")
text_replace_9 = text_replace_8.replace(")", " ) ")
text_replace_10 = text_replace_9.replace("/", " / ")
text_replace_11 = text_replace_10.replace("الله", "اللّٰـه")
text_split_list = text_replace_11.split()
count_number = []
letter_count_list = []
index_list = itertools.cycle(range(1, 4))
for letter_count in text_split_list:
if letter_count in interpunction_list:
letter_count_list.append(letter_count)
elif "ـ" in letter_count:
letter_count = len(letter_count) - 1
count_number.append(letter_count)
print(letter_count)
else:
letter_count = len(letter_count)
count_number.append(letter_count)
print(letter_count)
for count in count_number:
letter_count_list.append(letter_count * ".")
zip_list = zip(text_split_list, letter_count_list)
zip_list_result = list(zip_list)
for word, count in zip_list_result:
if ((len(word)) == 2 or word == "a" or word == "و") and not word in interpunction_list :
print(f" {{{{c{(next(index_list))}::{word}::{count}}}}}", end="")
elif word and count in interpunction_list:
print(word, end = "")
else:
print(f" {{{{c{(next(index_list))}::{word}::{count}}}}}", end="")
when I type كتب عليـ ـنا و علـ ـي
the return is {{c1::كتب::...}} {{c2::عليـ::...}} {{c3::ـنا::...}} {{c1::و::..}} {{c2::علـ::..}} {{c3::ـي::..}}
but it should be
{{c1::كتب::...}} {{c2::عليـ::...}} {{c3::ـنا::..}} {{c1::و::.}} {{c2::علـ::..}} {{c3::ـي::.}}
I add a print function the print the len() results and the result is correct but it add an extra dot in some case.
But when I type just a single "و" it does a correct len() function but when I input a whole sentence it add an extra dot and I don't know why.
please help

User input in panda, Can't stop the loop

Please see my below code, I'm trying to use user input to select specific rows within a dataframe. I'm not sure if it's my loop that is causing the issues? As when I run the code outside of the function the code seems to work. Any help would be great.
Thanks
def option3():
print("---------------------------")
print("please select from the following options")
print(Ndata[" workclass"].unique())
print("---------------------------")
loop3 = True
while loop3:
print("---------------------------")
Op1 = input('Please enter first working class: ')
Op2 = input('Please enter second working class: ')
print("Options selected ", Op1, "&", Op2)
print("---------------------------")
if Op1 and Op2 in Ndata[" workclass"]:
loop3 = False
sub = Ndata.loc[Ndata[" workclass"].isin([Op1, Op2])]
print("---------------------------")
print("PLease select frome the following")
print("[1] Most educated countries ")
print("[2] Marital status ")
print("---------------------------")
Op3 = int(input("PLease enter 1 or 2 : "))
loop4 = True
while loop4:
if Op3 == 1 or 2 :
loop4 = False
else:
print('PLease select 1 or 2')
else:
print("Please check", Op1, "&", Op2, " are in the working class")
print(Ndata[" workclass"].unique())

Store Groovy SQL result as a variable?

I am very, very new to Groovy (like two days in). I am trying to take a SQL result which will return a single value, and store that value so that it can be put in the body of an email. However, my SQL result always returns NULL, but the other values in the email work just fine.
I know that the result will only return a single value, so how in the world can I get that value stored as a string?
def sql = getSqlInstance()
def user = "\'" + trmCurrentUser.username + "\'";
def name = "\'" + trmCurrentUser.displayname + "\'";
def email = "\'" + trmCurrentUser.email + "\'";
def comm = "\'" + trmComponent.id + "\'";
def rslt=[];
def cmpgn;
rslt[0] = sql.firstRow("select activity_id from DB.TABLE where communication_id=${comm}");
def cmpgn = rslt[0];
toAddress = trmCurrentUser.email;
fromAddress = "me#email.com";
trmUtilities.sendEmail (
//self explanatory
toAddress, fromAddress,
//body of email
user + " " + name + " " + email + " " + comm + " " + cmpgn[0],
//subject of email
" Action on " + trmComponent.componentType + " " + trmComponent.name
);
The resulting email I get is this (with the appropriate values other than the NULL):
'MYID' 'MY NAME' 'MYEMAIL' 'COMM' null

How to get a list of failed job from SGE

How do I get a list of (recently) failed jobs (failed=100 or exit_status=137) from the SGE? From the qacct help:
[-j [job_id|job_name|pattern]] list all [matching] jobs
How do I use the pattern? I tried the following, does not work.
qacct -j failed=100
"pattern" in this case refers to a simple globbing expression to match against a job name, e.g. qacct -j 'myjob*'
qacct unfortunately doesn't have the filtration capability you're looking for - it's possible to filter on complex job attributes, but not fundamental ones like exit_status or failed.
You CAN retrieve that information from the SGE accounting file(assuming you have access to it) with just a little work. When SGE finishes a job, it writes out a simple record to $SGE_ROOT/$SGE_CELL/common/accounting - this is the file that qacct reads. You'll want to check the accounting(5) man page on your qmaster for details specific to your GridEngine version, but a job record in your accounting file should more or less look like this:
all.q:myexechost:group:user:myjobstep16:1126971:sge:0:1369755166:1369768897:1369769771:0:0:874:796.564903:30.676336:15788.000000:0:0:0:0:17009:2:0:47987400.000000:34033048:0:0:0:9468:27604:NONE:defaultdepartment:NONE:1:0:827.241239:96.445328:39.111400:-q all.q:0.000000:NONE:237133824.000000:0:0
In this particular record, failed and exit_status are the 12th and 13th fields, respectively. For a quick and dirty "recent failures" list, we can use these along with fields 6(job id) and 11(job end time) like so to reveal any failures in the most recent 100 jobs:
$ cut -d':' -f6,11,12,13 $SGE_ROOT/$SGE_CELL/common/accounting|sort -t':' -k2|tail -100|grep ':100:137'
I wrote a python script to parse the accounting file for failed jobs. You should edit it to your own use.
#!/usr/local/bin/python2.7
import os
from sys import *
import sys
import getopt
import datetime
#Variables
program = "parse_acct.py"
ifile = "/local/cluster/sge/default/common/accounting"
failed = 0
failedswitch = 0
subtime = 0
subtimeswitch = 0
begtime = 0
begtimeswitch = 0
endtime = 0
endtimeswitch = 0
user = 0
userswitch = 0
node = ""
nodeswitch = 0
### Read command line args
try:
myopts, args = getopt.getopt(sys.argv[1:],"i:f:n:t:u:b:e:h")
except getopt.GetoptError:
print program + " -i <input> -u <username> -n <node_name> -f"
sys.exit(2)
###############################
# o == option
# a == argument passed to the o
###############################
for o, a in myopts:
if o == '-f':
failed = a
failedswitch = 1
elif o == '-i':
ifile = a
elif o == '-u':
user = a
userswitch = 1
elif o == '-t':
subtime = a
subtimeswitch = 1
elif o == '-b':
begtime = a
begtimeswitch = 1
elif o == '-e':
endtime = a
endtimeswitch = 1
elif o == '-n':
node = a
nodeswitch = 1
elif o == '-h':
print program + " -i <input> -u <username> -n <node_name> -f"
sys.exit(0)
else:
print("Usage: %s -i <input> -u <username> -n <node_name> -f" % sys.argv[0])
sys.exit(0)
### --- Read line by line and import in to a list of lists --- ###
loi = []
f = open(ifile, "r")
for var in f:
line = var.rstrip().split(":")
if len(line) >= 10:
loi.append(line)
#print line
f.close()
### --- Parse through the list of lists and put a 0 to the beginning if it fails a test --- ###
for i in range(len(loi)):
if failedswitch == 1 and loi[i][11] >= 1: #!= failed:
loi[i][0] = [0]
elif userswitch == 1 and loi[i][3] != user:
loi[i][0] = [0]
elif nodeswitch == 1 and node != loi[i][1]:
loi[i][0] = [0]
# elif nodeswitch == 1 and node not in loi[i][1]:
# loi[i][0] = [0]
# elif nodeswitch == 1 and node not in loi[i][1]:
# loi[i][0] = [0]
# elif nodeswitch == 1 and node not in loi[i][1]:
# loi[i][0] = [0]
# elif nodeswitch == 1 and node not in loi[i][1]:
# loi[i][0] = [0]
### --- Remove all entries that have the "0" at the beginning --- ###
loidedup = [x for x in loi if x[0] != [0]
### --- Print out the files that passed all tests --- ###
for i in range(len(loidedup)):
print "=============================================================="
print "qname " + loidedup[i][0]
print "hostname " + loidedup[i][1]
print "group " + loidedup[i][2]
print "owner " + loidedup[i][3]
print "job_name " + loidedup[i][4]
print "job_number " + loidedup[i][5]
print "account " + loidedup[i][6]
print "priority " + loidedup[i][7]
print "submission_time " + datetime.datetime.fromtimestamp(int(loidedup[i][8])).strftime('%Y-%m-%d %H:%M:%S')
print "start_time " + datetime.datetime.fromtimestamp(int(loidedup[i][9])).strftime('%Y-%m-%d %H:%M:%S')
print "end_time " + datetime.datetime.fromtimestamp(int(loidedup[i][10])).strftime('%Y-%m-%d %H:%M:%S')
print "failed " + loidedup[i][11]
print "exit_status " + loidedup[i][12]
print "ru_wallclock " + loidedup[i][13]
print " ru_utime " + loidedup[i][14]
print " ru_stime " + loidedup[i][15]
print " ru_maxrss " + loidedup[i][16]
print " ru_ixrss " + loidedup[i][17]
print " ru_ismrss " + loidedup[i][18]
print " ru_idrss " + loidedup[i][19]
print " ru_isrss " + loidedup[i][20]
print " ru_minflt " + loidedup[i][21]
print " ru_majflt " + loidedup[i][22]
print " ru_nswap " + loidedup[i][23]
print " ru_inblock " + loidedup[i][24]
print " ru_oublock " + loidedup[i][25]
print " ru_msgsnd " + loidedup[i][26]
print " ru_msgrcv " + loidedup[i][27]
print " ru_nsignals " + loidedup[i][28]
print " ru_nvcsw " + loidedup[i][29]
print " ru_nivcsw " + loidedup[i][30]
print "project " + loidedup[i][31]
print "department " + loidedup[i][32]
print "granted_pe " + loidedup[i][33]
print "slots " + loidedup[i][34]
print "task_number " + loidedup[i][35]
print "cpu " + loidedup[i][36]
print "mem " + loidedup[i][37]
print "io " + loidedup[i][38]
print "category " + loidedup[i][39]
print "iow " + loidedup[i][40]
print "pe_taskid " + loidedup[i][41]
print "maxvmem " + loidedup[i][42]
print "arid " + loidedup[i][43]
print "ar_submission_time " + loidedup[i][44]
# print loidedup[i]

groovy closure instantiate variables

is it possible to create a set of variables from a list of values using a closure??
the reason for asking this is to create some recursive functionality based on a list of (say) two three four or five parts
The code here of course doesn't work but any pointers would be helpful.then
def longthing = 'A for B with C in D on E'
//eg shopping for 30 mins with Fiona in Birmingham on Friday at 15:00
def breaks = [" on ", " in ", "with ", " for "]
def vary = ['when', 'place', 'with', 'event']
i = 0
line = place = with = event = ""
breaks.each{
shortline = longthing.split(breaks[i])
longthing= shortline[0]
//this is the line which obviously will not work
${vary[i]} = shortline[1]
rez[i] = shortline[1]
i++
}
return place + "; " + with + "; " + event
// looking for answer of D; C; B
EDIT>>
Yes I am trying to find a groovier way to clean up this, which i have to do after the each loop
len = rez[3].trim()
if(len.contains("all")){
len = "all"
} else if (len.contains(" ")){
len = len.substring(0, len.indexOf(" ")+2 )
}
len = len.replaceAll(" ", "")
with = rez[2].trim()
place = rez[1].trim()
when = rez[0].trim()
event = shortline[0]
and if I decide to add another item to the list (which I just did) I have to remember which [i] it is to extract it successfully
This is the worker part for then parsing dates/times to then use jChronic to convert natural text into Gregorian Calendar info so I can then set an event in a Google Calendar
How about:
def longthing = 'A for B with C in D on E'
def breaks = [" on ", " in ", "with ", " for "]
def vary = ['when', 'place', 'with', 'event']
rez = []
line = place = with = event = ""
breaks.eachWithIndex{ b, i ->
shortline = longthing.split(b)
longthing = shortline[0]
this[vary[i]] = shortline[1]
rez[i] = shortline[1]
}
return place + "; " + with + "; " + event
when you use a closure with a List and "each", groovy loops over the element in the List, putting the value in the list in the "it" variable. However, since you also want to keep track of the index, there is a groovy eachWithIndex that also passes in the index
http://groovy.codehaus.org/GDK+Extensions+to+Object
so something like
breaks.eachWithIndex {item, index ->
... code here ...
}