Run 2to3 to start moving to python3

This commit is contained in:
Robert Maikher 2018-08-19 16:38:45 +02:00
parent f155d21ae0
commit ce56649c7c
16 changed files with 259 additions and 264 deletions

View File

@ -1,4 +1,4 @@
db_url = 'postgres://CVi@127.0.0.1/pvv_vv' db_url = 'postgres://robertem@127.0.0.1/pvvvv'
quit_allowed = True quit_allowed = True
stop_allowed = False stop_allowed = False
show_tracebacks = True show_tracebacks = True

View File

@ -104,13 +104,13 @@ def argmax(d, all=False, value=None):
if value != None: if value != None:
dd = d dd = d
d = {} d = {}
for key in dd.keys(): for key in list(dd.keys()):
d[key] = value(dd[key]) d[key] = value(dd[key])
for key in d.keys(): for key in list(d.keys()):
if maxarg == None or d[key] > d[maxarg]: if maxarg == None or d[key] > d[maxarg]:
maxarg = key maxarg = key
if all: if all:
return filter(lambda k: d[k] == d[maxarg], d.keys()) return [k for k in list(d.keys()) if d[k] == d[maxarg]]
return maxarg return maxarg
def safe_str(obj): def safe_str(obj):
@ -122,10 +122,10 @@ def safe_str(obj):
''' '''
if isinstance(obj, str): if isinstance(obj, str):
return obj return obj
if isinstance(obj, unicode): if isinstance(obj, str):
return obj.encode('utf8') return obj.encode('utf8')
else: else:
return safe_str(unicode(obj)) return safe_str(str(obj))
def less(string): def less(string):
''' '''

View File

@ -6,4 +6,4 @@ session=Session()
slabbedasker=session.query(User).filter(User.credit<0).all() slabbedasker=session.query(User).filter(User.credit<0).all()
for slubbert in slabbedasker: for slubbert in slabbedasker:
print "%s, %s" % (slubbert.name, slubbert.credit) print("%s, %s" % (slubbert.name, slubbert.credit))

View File

@ -7,29 +7,29 @@ import matplotlib.dates as mdates
def getInputType(): def getInputType():
inp = 0 inp = 0
while not (inp == '1' or inp == '2' or inp == '3' or inp == '4'): while not (inp == '1' or inp == '2' or inp == '3' or inp == '4'):
print 'type 1 for user-statistics' print('type 1 for user-statistics')
print 'type 2 for product-statistics' print('type 2 for product-statistics')
print 'type 3 for global-statistics' print('type 3 for global-statistics')
print 'type 4 to enter loop-mode' print('type 4 to enter loop-mode')
inp = raw_input('') inp = input('')
return int(inp) return int(inp)
def getDateFile(date, n): def getDateFile(date, n):
try: try:
if n==0: if n==0:
inp = raw_input('start date? (yyyy-mm-dd) ') inp = input('start date? (yyyy-mm-dd) ')
elif n==-1: elif n==-1:
inp = raw_input('end date? (yyyy-mm-dd) ') inp = input('end date? (yyyy-mm-dd) ')
year = inp.partition('-') year = inp.partition('-')
month = year[2].partition('-') month = year[2].partition('-')
return datetime.date(int(year[0]), int(month[0]), int(month[2])) return datetime.date(int(year[0]), int(month[0]), int(month[2]))
except: except:
print 'invalid date, setting start start date' print('invalid date, setting start start date')
if n==0: if n==0:
print 'to date found on first line' print('to date found on first line')
elif n==-1: elif n==-1:
print 'to date found on last line' print('to date found on last line')
print date print(date)
return datetime.date(int(date.partition('-')[0]), int(date.partition('-')[2].partition('-')[0]), int(date.partition('-')[2].partition('-')[2])) return datetime.date(int(date.partition('-')[0]), int(date.partition('-')[2].partition('-')[0]), int(date.partition('-')[2].partition('-')[2]))
def dateToDateNumFile(date, startDate): def dateToDateNumFile(date, startDate):
@ -72,8 +72,8 @@ def dayPlot(array, days):
if (not array == []): if (not array == []):
for i in range(7): for i in range(7):
array[i]=array[i]*7.0/days array[i]=array[i]*7.0/days
plt.bar(range(7), array) plt.bar(list(range(7)), array)
plt.xticks(range(7),[' mon',' tue',' wed',' thu',' fri',' sat',' sun']) plt.xticks(list(range(7)),[' mon',' tue',' wed',' thu',' fri',' sat',' sun'])
def graphPlot(array, dateLine): def graphPlot(array, dateLine):
if (not array == []): if (not array == []):
@ -135,22 +135,22 @@ def plotGlobal(database, dateLine, n):
def alt4menu(database, dateLine, useDatabase): def alt4menu(database, dateLine, useDatabase):
n=10 n=10
while 1: while 1:
print '\n1: user-statistics, 2: product-statistics, 3:global-statistics, n: adjust amount of data shown q:quit' print('\n1: user-statistics, 2: product-statistics, 3:global-statistics, n: adjust amount of data shown q:quit')
try: try:
inp = raw_input('') inp = input('')
except: except:
continue continue
if inp == 'q': if inp == 'q':
break break
elif inp == '1': elif inp == '1':
if i=='0': if i=='0':
user = raw_input('input full username: ') user = input('input full username: ')
else: else:
user = getUser() user = getUser()
plotUser(database, dateLine, user, n) plotUser(database, dateLine, user, n)
elif inp == '2': elif inp == '2':
if i=='0': if i=='0':
product = raw_input('input full product name: ') product = input('input full product name: ')
else: else:
product = getProduct() product = getProduct()
plotProduct(database, dateLine, product, n) plotProduct(database, dateLine, product, n)
@ -158,21 +158,21 @@ def alt4menu(database, dateLine, useDatabase):
plotGlobal(database, dateLine, n) plotGlobal(database, dateLine, n)
elif inp == 'n': elif inp == 'n':
try: try:
n=int(raw_input('set number to show ')); n=int(input('set number to show '));
except: except:
pass pass
#---------------------------------------MAIN------------------------------------- #---------------------------------------MAIN-------------------------------------
inputType=getInputType() inputType=getInputType()
i = raw_input('0:fil, 1:database \n? ') i = input('0:fil, 1:database \n? ')
if (inputType == 1): if (inputType == 1):
if i=='0': if i=='0':
user = raw_input('input full username: ') user = input('input full username: ')
else: else:
user = getUser() user = getUser()
product = '' product = ''
elif (inputType == 2): elif (inputType == 2):
if i=='0': if i=='0':
product = raw_input('input full product name: ') product = input('input full product name: ')
else: else:
product = getProduct() product = getProduct()
user = '' user = ''
@ -180,7 +180,7 @@ else :
product = '' product = ''
user = '' user = ''
if i=='0': if i=='0':
inputFile=raw_input('logfil? ') inputFile=input('logfil? ')
if inputFile=='': if inputFile=='':
inputFile='default.dibblerlog' inputFile='default.dibblerlog'
database, dateLine = buildDatabaseFromFile(inputFile, inputType, product, user) database, dateLine = buildDatabaseFromFile(inputFile, inputType, product, user)

View File

@ -9,7 +9,7 @@ import db
def getUser(): def getUser():
while 1: while 1:
string = raw_input('user? ') string = input('user? ')
session = Session() session = Session()
user = search_user(string, session) user = search_user(string, session)
session.close() session.close()
@ -17,25 +17,25 @@ def getUser():
return user.name return user.name
i=0 i=0
if len(user)==0: if len(user)==0:
print 'no matching string' print('no matching string')
if len(user)==1: if len(user)==1:
print 'antar: ', user[0].name, '\n' print('antar: ', user[0].name, '\n')
return user[0].name return user[0].name
if len(user)>10: if len(user)>10:
continue continue
for u in user: for u in user:
print i, u.name print(i, u.name)
i += 1 i += 1
try: try:
n = int(raw_input ('enter number:')) n = int(input ('enter number:'))
except: except:
print 'invalid input, restarting' print('invalid input, restarting')
continue continue
if (n>-1) and (n<i): if (n>-1) and (n<i):
return user[n].name return user[n].name
def getProduct(): def getProduct():
while 1: while 1:
string = raw_input('product? ') string = input('product? ')
session = Session() session = Session()
product = search_product(string, session) product = search_product(string, session)
session.close() session.close()
@ -43,19 +43,19 @@ def getProduct():
return product.name return product.name
i=0 i=0
if len(product)==0: if len(product)==0:
print 'no matching string' print('no matching string')
if len(product)==1: if len(product)==1:
print 'antar: ', product[0].name, '\n' print('antar: ', product[0].name, '\n')
return product[0].name return product[0].name
if len(product)>10: if len(product)>10:
continue continue
for u in product: for u in product:
print i, u.name print(i, u.name)
i += 1 i += 1
try: try:
n = int(raw_input ('enter number:')) n = int(input ('enter number:'))
except: except:
print 'invalid input, restarting' print('invalid input, restarting')
continue continue
if (n>-1) and (n<i): if (n>-1) and (n<i):
return product[n].name return product[n].name
@ -94,8 +94,8 @@ def getDateDb(date, inp):
month = year[2].partition('-') month = year[2].partition('-')
return datetime.datetime(int(year[0]), int(month[0]), int(month[2])) return datetime.datetime(int(year[0]), int(month[0]), int(month[2]))
except: except:
print 'invalid date, setting date to date found in db' print('invalid date, setting date to date found in db')
print date print(date)
return date return date
def dateToDateNumDb(date, startDate): def dateToDateNumDb(date, startDate):
@ -105,11 +105,11 @@ def dateToDateNumDb(date, startDate):
def getInputType(): def getInputType():
inp = 0 inp = 0
while not (inp == '1' or inp == '2' or inp == '3' or inp == '4'): while not (inp == '1' or inp == '2' or inp == '3' or inp == '4'):
print 'type 1 for user-statistics' print('type 1 for user-statistics')
print 'type 2 for product-statistics' print('type 2 for product-statistics')
print 'type 3 for global-statistics' print('type 3 for global-statistics')
print 'type 4 to enter loop-mode' print('type 4 to enter loop-mode')
inp = raw_input('') inp = input('')
return int(inp) return int(inp)
def getProducts(products): def getProducts(products):
@ -127,8 +127,8 @@ def getDateFile(date, inp):
month = year[2].partition('-') month = year[2].partition('-')
return datetime.date(int(year[0]), int(month[0]), int(month[2])) return datetime.date(int(year[0]), int(month[0]), int(month[2]))
except: except:
print 'invalid date, setting date to date found on file file' print('invalid date, setting date to date found on file file')
print date print(date)
return datetime.date(int(date.partition('-')[0]), int(date.partition('-')[2].partition('-')[0]), int(date.partition('-')[2].partition('-')[2])) return datetime.date(int(date.partition('-')[0]), int(date.partition('-')[2].partition('-')[0]), int(date.partition('-')[2].partition('-')[2]))
def dateToDateNumFile(date, startDate): def dateToDateNumFile(date, startDate):
@ -199,9 +199,9 @@ def addLineToDatabase(database, inputLine):
return database return database
def buildDatabaseFromDb(inputType, inputProduct, inputUser): def buildDatabaseFromDb(inputType, inputProduct, inputUser):
sdate = raw_input('enter start date (yyyy-mm-dd)? ') sdate = input('enter start date (yyyy-mm-dd)? ')
edate = raw_input('enter end date (yyyy-mm-dd)? ') edate = input('enter end date (yyyy-mm-dd)? ')
print 'building database...' print('building database...')
session = Session() session = Session()
transaction_list = session.query(Transaction).all() transaction_list = session.query(Transaction).all()
inputLine = InputLine(inputUser, inputProduct, inputType) inputLine = InputLine(inputUser, inputProduct, inputType)
@ -216,10 +216,10 @@ def buildDatabaseFromDb(inputType, inputProduct, inputUser):
database.globalDatoForbruk = [0]*(inputLine.numberOfDays+1) database.globalDatoForbruk = [0]*(inputLine.numberOfDays+1)
database.globalUkedagForbruk = [0]*7 database.globalUkedagForbruk = [0]*7
database.pengebeholdning = [0]*(inputLine.numberOfDays+1) database.pengebeholdning = [0]*(inputLine.numberOfDays+1)
print 'wait for it.... ' print('wait for it.... ')
for transaction in transaction_list: for transaction in transaction_list:
if transaction.purchase: if transaction.purchase:
products = map(lambda ent: ent.product.name, transaction.purchase.entries) products = [ent.product.name for ent in transaction.purchase.entries]
else: else:
products = [] products = []
products.append('') products.append('')
@ -232,13 +232,13 @@ def buildDatabaseFromDb(inputType, inputProduct, inputUser):
database=addLineToDatabase(database, inputLine ) database=addLineToDatabase(database, inputLine )
inputLine.price = 0; inputLine.price = 0;
print 'saving as default.dibblerlog...', print('saving as default.dibblerlog...', end=' ')
f=open('default.dibblerlog','w') f=open('default.dibblerlog','w')
line_format = '%s|%s|%s|%s|%s|%s\n' line_format = '%s|%s|%s|%s|%s|%s\n'
transaction_list = session.query(Transaction).all() transaction_list = session.query(Transaction).all()
for transaction in transaction_list: for transaction in transaction_list:
if transaction.purchase: if transaction.purchase:
products = u'¤'.join(map(lambda ent: ent.product.name, transaction.purchase.entries)) products = '¤'.join([ent.product.name for ent in transaction.purchase.entries])
description = '' description = ''
else: else:
products = '' products = ''
@ -258,12 +258,12 @@ def buildDatabaseFromDb(inputType, inputProduct, inputUser):
dateLine.append(startDate) dateLine.append(startDate)
for n in range(inputLine.numberOfDays): for n in range(inputLine.numberOfDays):
dateLine.append(startDate+n*day) dateLine.append(startDate+n*day)
print 'done' print('done')
return database, dateLine return database, dateLine
def buildDatabaseFromFile(inputFile, inputType, inputProduct, inputUser): def buildDatabaseFromFile(inputFile, inputType, inputProduct, inputUser):
sdate = raw_input('enter start date (yyyy-mm-dd)? ') sdate = input('enter start date (yyyy-mm-dd)? ')
edate = raw_input('enter end date (yyyy-mm-dd)? ') edate = input('enter end date (yyyy-mm-dd)? ')
f=open(inputFile) f=open(inputFile)
try: try:
@ -315,18 +315,18 @@ def buildDatabaseFromFile(inputFile, inputType, inputProduct, inputUser):
def printTopDict(dictionary, n, k): def printTopDict(dictionary, n, k):
i=0 i=0
for key in sorted(dictionary, key=dictionary.get, reverse=k): for key in sorted(dictionary, key=dictionary.get, reverse=k):
print key, ': ',dictionary[key] print(key, ': ',dictionary[key])
if i<n: if i<n:
i += 1 i += 1
else: else:
break break
def printTopDict2(dictionary, dictionary2, n): def printTopDict2(dictionary, dictionary2, n):
print '' print('')
print 'product : price[kr] ( number )' print('product : price[kr] ( number )')
i=0 i=0
for key in sorted(dictionary, key=dictionary.get, reverse=True): for key in sorted(dictionary, key=dictionary.get, reverse=True):
print key, ': ',dictionary[key], ' (', dictionary2[key], ') ' print(key, ': ',dictionary[key], ' (', dictionary2[key], ') ')
if i<n: if i<n:
i += 1 i += 1
else: else:
@ -335,80 +335,80 @@ def printTopDict2(dictionary, dictionary2, n):
def printWeekdays(week, days): def printWeekdays(week, days):
if week==[] or days==0: if week==[] or days==0:
return return
print 'mon: ', '%.2f'%(week[0]*7.0/days), ' tue: ', '%.2f'%(week[1]*7.0/days), ' wen: ', '%.2f'%(week[2]*7.0/days), ' thu: ', '%.2f'%(week[3]*7.0/days), ' fri: ', '%.2f'%(week[4]*7.0/days), ' sat: ','%.2f'%( week[5]*7.0/days), ' sun: ', '%.2f'%(week[6]*7.0/days) print('mon: ', '%.2f'%(week[0]*7.0/days), ' tue: ', '%.2f'%(week[1]*7.0/days), ' wen: ', '%.2f'%(week[2]*7.0/days), ' thu: ', '%.2f'%(week[3]*7.0/days), ' fri: ', '%.2f'%(week[4]*7.0/days), ' sat: ','%.2f'%( week[5]*7.0/days), ' sun: ', '%.2f'%(week[6]*7.0/days))
print 'forbruk per dag (snitt): ', '%.2f'%(sum(week)*1.0/days) print('forbruk per dag (snitt): ', '%.2f'%(sum(week)*1.0/days))
print '' print('')
def printBalance(database, user): def printBalance(database, user):
forbruk = 0 forbruk = 0
if (user in database.personVareVerdi): if (user in database.personVareVerdi):
forbruk = sum([i for i in database.personVareVerdi[user].values()]) forbruk = sum([i for i in list(database.personVareVerdi[user].values())])
print 'totalt kjøpt for: ', forbruk, print('totalt kjøpt for: ', forbruk, end=' ')
if (user in database.personNegTransactions): if (user in database.personNegTransactions):
print 'kr, totalt lagt til: ', -database.personNegTransactions[user], print('kr, totalt lagt til: ', -database.personNegTransactions[user], end=' ')
forbruk=-database.personNegTransactions[user]-forbruk forbruk=-database.personNegTransactions[user]-forbruk
if (user in database.personPosTransactions): if (user in database.personPosTransactions):
print 'kr, totalt tatt fra boks: ', database.personPosTransactions[user], print('kr, totalt tatt fra boks: ', database.personPosTransactions[user], end=' ')
forbruk=forbruk-database.personPosTransactions[user] forbruk=forbruk-database.personPosTransactions[user]
print 'balanse: ', forbruk, 'kr', print('balanse: ', forbruk, 'kr', end=' ')
print '' print('')
def printUser(database, dateLine, user, n): def printUser(database, dateLine, user, n):
printTopDict2(database.personVareVerdi[user], database.personVareAntall[user], n) printTopDict2(database.personVareVerdi[user], database.personVareAntall[user], n)
print '\nforbruk per ukedag [kr/dag],', print('\nforbruk per ukedag [kr/dag],', end=' ')
printWeekdays(database.personUkedagVerdi[user], len(dateLine)) printWeekdays(database.personUkedagVerdi[user], len(dateLine))
printBalance(database, user) printBalance(database, user)
def printProduct(database, dateLine, product, n): def printProduct(database, dateLine, product, n):
printTopDict(database.varePersonAntall[product], n, 1) printTopDict(database.varePersonAntall[product], n, 1)
print '\nforbruk per ukedag [antall/dag],', print('\nforbruk per ukedag [antall/dag],', end=' ')
printWeekdays(database.vareUkedagAntall[product], len(dateLine)) printWeekdays(database.vareUkedagAntall[product], len(dateLine))
print 'Det er solgt: ', database.globalVareAntall[product], product, 'til en verdi av: ', database.globalVareVerdi[product], 'kr' print('Det er solgt: ', database.globalVareAntall[product], product, 'til en verdi av: ', database.globalVareVerdi[product], 'kr')
def printGlobal(database, dateLine, n): def printGlobal(database, dateLine, n):
print '\nmest lagt til: ' print('\nmest lagt til: ')
printTopDict(database.personNegTransactions, n, 0) printTopDict(database.personNegTransactions, n, 0)
print '\nmest tatt fra:' print('\nmest tatt fra:')
printTopDict(database.personPosTransactions, n, 1) printTopDict(database.personPosTransactions, n, 1)
print '\nstørst forbruk:' print('\nstørst forbruk:')
printTopDict(database.globalPersonForbruk, n, 1) printTopDict(database.globalPersonForbruk, n, 1)
printTopDict2(database.globalVareVerdi, database.globalVareAntall, n) printTopDict2(database.globalVareVerdi, database.globalVareAntall, n)
print '\nforbruk per ukedag [kr/dag],', print('\nforbruk per ukedag [kr/dag],', end=' ')
printWeekdays(database.globalUkedagForbruk, len(dateLine)) printWeekdays(database.globalUkedagForbruk, len(dateLine))
print 'Det er solgt varer til en verdi av: ', sum(database.globalDatoForbruk), 'kr, det er lagt til', -sum([i for i in database.personNegTransactions.values()]), 'og tatt fra', sum([i for i in database.personPosTransactions.values()]), print('Det er solgt varer til en verdi av: ', sum(database.globalDatoForbruk), 'kr, det er lagt til', -sum([i for i in list(database.personNegTransactions.values())]), 'og tatt fra', sum([i for i in list(database.personPosTransactions.values())]), end=' ')
print 'balansen blir:', database.pengebeholdning[len(dateLine)-1], 'der negative verdier representerer at brukere har kreditt tilgjengelig' print('balansen blir:', database.pengebeholdning[len(dateLine)-1], 'der negative verdier representerer at brukere har kreditt tilgjengelig')
def alt4menuTextOnly(database, dateLine): def alt4menuTextOnly(database, dateLine):
n=10 n=10
while 1: while 1:
print '\n1: user-statistics, 2: product-statistics, 3:global-statistics, n: adjust amount of data shown q:quit' print('\n1: user-statistics, 2: product-statistics, 3:global-statistics, n: adjust amount of data shown q:quit')
inp = raw_input('') inp = input('')
if inp == 'q': if inp == 'q':
break break
elif inp == '1': elif inp == '1':
try: try:
printUser(database, dateLine, getUser(), n) printUser(database, dateLine, getUser(), n)
except: except:
print '\n\nSomething is not right, (last date prior to first date?)' print('\n\nSomething is not right, (last date prior to first date?)')
elif inp == '2': elif inp == '2':
try: try:
printProduct(database, dateLine, getProduct(), n) printProduct(database, dateLine, getProduct(), n)
except: except:
print '\n\nSomething is not right, (last date prior to first date?)' print('\n\nSomething is not right, (last date prior to first date?)')
elif inp == '3': elif inp == '3':
try: try:
printGlobal(database, dateLine, n) printGlobal(database, dateLine, n)
except: except:
print '\n\nSomething is not right, (last date prior to first date?)' print('\n\nSomething is not right, (last date prior to first date?)')
elif inp == 'n': elif inp == 'n':
n=int(raw_input('set number to show ')); n=int(input('set number to show '));
def statisticsTextOnly(): def statisticsTextOnly():
inputType = 4 inputType = 4
product = '' product = ''
user = '' user = ''
print '\n0: from file, 1: from database, q:quit' print('\n0: from file, 1: from database, q:quit')
inp = raw_input('') inp = input('')
if inp == '1': if inp == '1':
database, dateLine = buildDatabaseFromDb(inputType, product, user) database, dateLine = buildDatabaseFromDb(inputType, product, user)
elif inp=='0' or inp == '': elif inp=='0' or inp == '':

View File

@ -60,13 +60,13 @@ if __name__ == '__main__':
try: try:
main.execute() main.execute()
except KeyboardInterrupt: except KeyboardInterrupt:
print '' print('')
print 'Interrupted.' print('Interrupted.')
except: except:
print 'Something went wrong.' print('Something went wrong.')
print '%s: %s' % (sys.exc_info()[0], sys.exc_info()[1]) print('%s: %s' % (sys.exc_info()[0], sys.exc_info()[1]))
if conf.show_tracebacks: if conf.show_tracebacks:
traceback.print_tb(sys.exc_info()[2]) traceback.print_tb(sys.exc_info()[2])
else: else:
break break
print 'Restarting main menu.' print('Restarting main menu.')

View File

@ -66,36 +66,36 @@ much money you're due in credits for the purchase when prompted.\n'''
return bool(self.users) and len(self.products) and self.price return bool(self.users) and len(self.products) and self.price
def print_info(self): def print_info(self):
print (6 + Product.name_length) * '-' print((6 + Product.name_length) * '-')
if self.price: if self.price:
print "Amount to be credited: {{0:>{0}d}}".format(Product.name_length-17).format(self.price) print("Amount to be credited: {{0:>{0}d}}".format(Product.name_length-17).format(self.price))
if self.users: if self.users:
print "Users to credit:" print("Users to credit:")
for user in self.users: for user in self.users:
print " %s" % str(user.name) print(" %s" % str(user.name))
print u"\n{{0:s}}{{1:>{0}s}}".format(Product.name_length-1).format("Product", "Amount") print("\n{{0:s}}{{1:>{0}s}}".format(Product.name_length-1).format("Product", "Amount"))
print (6 + Product.name_length) * '-' print((6 + Product.name_length) * '-')
if len(self.products): if len(self.products):
for product in self.products.keys(): for product in list(self.products.keys()):
print u'{{0:<{0}}}{{1:>6d}}'.format(Product.name_length).format(product.name, self.products[product][0]) print('{{0:<{0}}}{{1:>6d}}'.format(Product.name_length).format(product.name, self.products[product][0]))
print (6 + Product.name_length) * '-' print((6 + Product.name_length) * '-')
def add_thing_to_pending(self, thing, amount, price): def add_thing_to_pending(self, thing, amount, price):
if isinstance(thing, User): if isinstance(thing, User):
self.users.append(thing) self.users.append(thing)
elif thing in self.products.keys(): elif thing in list(self.products.keys()):
print 'Already added this product, adding amounts' print('Already added this product, adding amounts')
self.products[thing][0] += amount self.products[thing][0] += amount
self.products[thing][1] += price self.products[thing][1] += price
else: else:
self.products[thing] = [amount, price] self.products[thing] = [amount, price]
def perform_transaction(self): def perform_transaction(self):
print 'Did you pay a different price?' print('Did you pay a different price?')
if self.confirm('>', default=False): if self.confirm('>', default=False):
price = self.input_int('How much did you pay?', default=self.price) price = self.input_int('How much did you pay?', default=self.price)
if price > self.price: if price > self.price:
print 'Illegal action, total can not be higher than your total.' print('Illegal action, total can not be higher than your total.')
else: else:
self.price = price self.price = price
@ -109,9 +109,9 @@ much money you're due in credits for the purchase when prompted.\n'''
product.price = int(ceil(float(value) / (max(product.stock, 0) + self.products[product][0]))) product.price = int(ceil(float(value) / (max(product.stock, 0) + self.products[product][0])))
product.stock = max(self.products[product][0], product.stock + self.products[product][0]) product.stock = max(self.products[product][0], product.stock + self.products[product][0])
product.hidden = False product.hidden = False
print "New stock for %s: %d" % (product.name, product.stock), \ print("New stock for %s: %d" % (product.name, product.stock), \
("- New price: " + str(product.price) if old_price != product.price else ""), \ ("- New price: " + str(product.price) if old_price != product.price else ""), \
("- Removed hidden status" if old_hidden != product.hidden else "") ("- Removed hidden status" if old_hidden != product.hidden else ""))
purchase = Purchase() purchase = Purchase()
for user in self.users: for user in self.users:
@ -124,9 +124,9 @@ much money you're due in credits for the purchase when prompted.\n'''
try: try:
self.session.commit() self.session.commit()
print "Success! Transaction performed:" print("Success! Transaction performed:")
# self.print_info() # self.print_info()
for user in self.users: for user in self.users:
print "User %s's credit is now %i" % (user.name, user.credit) print("User %s's credit is now %i" % (user.name, user.credit))
except sqlalchemy.exc.SQLAlchemyError, e: except sqlalchemy.exc.SQLAlchemyError as e:
print 'Could not perform transaction: %s' % e print('Could not perform transaction: %s' % e)

View File

@ -34,29 +34,29 @@ When finished, write an empty line to confirm the purchase.\n'''
def low_credit_warning(self, user, timeout=False): def low_credit_warning(self, user, timeout=False):
assert isinstance(user, User) assert isinstance(user, User)
print "***********************************************************************" print("***********************************************************************")
print "***********************************************************************" print("***********************************************************************")
print "" print("")
print "$$\ $$\ $$$$$$\ $$$$$$$\ $$\ $$\ $$$$$$\ $$\ $$\ $$$$$$\\" print("$$\ $$\ $$$$$$\ $$$$$$$\ $$\ $$\ $$$$$$\ $$\ $$\ $$$$$$\\")
print "$$ | $\ $$ |$$ __$$\ $$ __$$\ $$$\ $$ |\_$$ _|$$$\ $$ |$$ __$$\\" print("$$ | $\ $$ |$$ __$$\ $$ __$$\ $$$\ $$ |\_$$ _|$$$\ $$ |$$ __$$\\")
print "$$ |$$$\ $$ |$$ / $$ |$$ | $$ |$$$$\ $$ | $$ | $$$$\ $$ |$$ / \__|" print("$$ |$$$\ $$ |$$ / $$ |$$ | $$ |$$$$\ $$ | $$ | $$$$\ $$ |$$ / \__|")
print "$$ $$ $$\$$ |$$$$$$$$ |$$$$$$$ |$$ $$\$$ | $$ | $$ $$\$$ |$$ |$$$$\\" print("$$ $$ $$\$$ |$$$$$$$$ |$$$$$$$ |$$ $$\$$ | $$ | $$ $$\$$ |$$ |$$$$\\")
print "$$$$ _$$$$ |$$ __$$ |$$ __$$< $$ \$$$$ | $$ | $$ \$$$$ |$$ |\_$$ |" print("$$$$ _$$$$ |$$ __$$ |$$ __$$< $$ \$$$$ | $$ | $$ \$$$$ |$$ |\_$$ |")
print "$$$ / \$$$ |$$ | $$ |$$ | $$ |$$ |\$$$ | $$ | $$ |\$$$ |$$ | $$ |" print("$$$ / \$$$ |$$ | $$ |$$ | $$ |$$ |\$$$ | $$ | $$ |\$$$ |$$ | $$ |")
print "$$ / \$$ |$$ | $$ |$$ | $$ |$$ | \$$ |$$$$$$\ $$ | \$$ |\$$$$$$ |" print("$$ / \$$ |$$ | $$ |$$ | $$ |$$ | \$$ |$$$$$$\ $$ | \$$ |\$$$$$$ |")
print "\__/ \__|\__| \__|\__| \__|\__| \__|\______|\__| \__| \______/" print("\__/ \__|\__| \__|\__| \__|\__| \__|\______|\__| \__| \______/")
print "" print("")
print "***********************************************************************" print("***********************************************************************")
print "***********************************************************************" print("***********************************************************************")
print "" print("")
print "USER %s HAS LOWER CREDIT THAN %d." % (user.name, conf.low_credit_warning_limit) print("USER %s HAS LOWER CREDIT THAN %d." % (user.name, conf.low_credit_warning_limit))
print "THIS PURCHASE WILL CHARGE YOUR CREDIT TWICE AS MUCH." print("THIS PURCHASE WILL CHARGE YOUR CREDIT TWICE AS MUCH.")
print "CONSIDER PUTTING MONEY IN THE BOX TO AVOID THIS." print("CONSIDER PUTTING MONEY IN THE BOX TO AVOID THIS.")
print "" print("")
print "Do you want to continue with this purchase?" print("Do you want to continue with this purchase?")
if timeout: if timeout:
print"THIS PURCHASE WILL AUTOMATICALLY BE PERFORMED IN 3 MINUTES!" print("THIS PURCHASE WILL AUTOMATICALLY BE PERFORMED IN 3 MINUTES!")
return self.confirm(prompt=">", default=True, timeout=180) return self.confirm(prompt=">", default=True, timeout=180)
else: else:
return self.confirm(prompt=">", default=True) return self.confirm(prompt=">", default=True)
@ -64,10 +64,10 @@ When finished, write an empty line to confirm the purchase.\n'''
def add_thing_to_purchase(self, thing, amount=1): def add_thing_to_purchase(self, thing, amount=1):
if isinstance(thing, User): if isinstance(thing, User):
if thing.is_anonymous(): if thing.is_anonymous():
print '---------------------------------------------' print('---------------------------------------------')
print '| You are now purchasing as the user anonym.|' print('| You are now purchasing as the user anonym.|')
print '| You have to put money in the anonym-jar. |' print('| You have to put money in the anonym-jar. |')
print '---------------------------------------------' print('---------------------------------------------')
if not self.credit_check(thing): if not self.credit_check(thing):
if self.low_credit_warning(user=thing, timeout=self.superfast_mode): if self.low_credit_warning(user=thing, timeout=self.superfast_mode):
@ -100,11 +100,11 @@ When finished, write an empty line to confirm the purchase.\n'''
if len(initial_contents) > 0 and all(map(is_product, initial_contents)): if len(initial_contents) > 0 and all(map(is_product, initial_contents)):
self.superfast_mode = True self.superfast_mode = True
print '***********************************************' print('***********************************************')
print '****** Buy menu is in SUPERFASTmode[tm]! ******' print('****** Buy menu is in SUPERFASTmode[tm]! ******')
print '*** The purchase will be stored immediately ***' print('*** The purchase will be stored immediately ***')
print '*** when you enter a user. ***' print('*** when you enter a user. ***')
print '***********************************************' print('***********************************************')
while True: while True:
self.print_purchase() self.print_purchase()
@ -148,17 +148,17 @@ When finished, write an empty line to confirm the purchase.\n'''
self.session.add(self.purchase) self.session.add(self.purchase)
try: try:
self.session.commit() self.session.commit()
except sqlalchemy.exc.SQLAlchemyError, e: except sqlalchemy.exc.SQLAlchemyError as e:
print 'Could not store purchase: %s' % e print('Could not store purchase: %s' % e)
else: else:
print 'Purchase stored.' print('Purchase stored.')
self.print_purchase() self.print_purchase()
for t in self.purchase.transactions: for t in self.purchase.transactions:
if not t.user.is_anonymous(): if not t.user.is_anonymous():
print 'User %s\'s credit is now %d kr' % (t.user.name, t.user.credit) print('User %s\'s credit is now %d kr' % (t.user.name, t.user.credit))
if t.user.credit < conf.low_credit_warning_limit: if t.user.credit < conf.low_credit_warning_limit:
print 'USER %s HAS LOWER CREDIT THAN %d, AND SHOULD CONSIDER PUTTING SOME MONEY IN THE BOX.' \ print('USER %s HAS LOWER CREDIT THAN %d, AND SHOULD CONSIDER PUTTING SOME MONEY IN THE BOX.' \
% (t.user.name, conf.low_credit_warning_limit) % (t.user.name, conf.low_credit_warning_limit))
return True return True
@ -177,15 +177,13 @@ When finished, write an empty line to confirm the purchase.\n'''
string += '(empty)' string += '(empty)'
else: else:
string += ', '.join( string += ', '.join(
map(lambda t: t.user.name + ("*" if not self.credit_check(t.user) else ""), [t.user.name + ("*" if not self.credit_check(t.user) else "") for t in transactions])
transactions))
string += '\n products: ' string += '\n products: '
if len(entries) == 0: if len(entries) == 0:
string += '(empty)' string += '(empty)'
else: else:
string += "\n " string += "\n "
string += '\n '.join(map(lambda e: '%dx %s (%d kr)' % (e.amount, e.product.name, e.product.price), string += '\n '.join(['%dx %s (%d kr)' % (e.amount, e.product.name, e.product.price) for e in entries])
entries))
if len(transactions) > 1: if len(transactions) > 1:
string += '\n price per person: %d kr' % self.purchase.price_per_transaction() string += '\n price per person: %d kr' % self.purchase.price_per_transaction()
if any(t.penalty > 1 for t in transactions): if any(t.penalty > 1 for t in transactions):

View File

@ -19,9 +19,9 @@ class AddUserMenu(Menu):
self.session.add(user) self.session.add(user)
try: try:
self.session.commit() self.session.commit()
print 'User %s stored' % username print('User %s stored' % username)
except sqlalchemy.exc.IntegrityError, e: except sqlalchemy.exc.IntegrityError as e:
print 'Could not store user %s: %s' % (username, e) print('Could not store user %s: %s' % (username, e))
self.pause() self.pause()
@ -56,9 +56,9 @@ user, then rfid (write an empty line to remove the card number or rfid).
empty_string_is_none=True) empty_string_is_none=True)
try: try:
self.session.commit() self.session.commit()
print 'User %s stored' % user.name print('User %s stored' % user.name)
except sqlalchemy.exc.SQLAlchemyError, e: except sqlalchemy.exc.SQLAlchemyError as e:
print 'Could not store user %s: %s' % (user.name, e) print('Could not store user %s: %s' % (user.name, e))
self.pause() self.pause()
@ -75,9 +75,9 @@ class AddProductMenu(Menu):
self.session.add(product) self.session.add(product)
try: try:
self.session.commit() self.session.commit()
print 'Product %s stored' % name print('Product %s stored' % name)
except sqlalchemy.exc.SQLAlchemyError, e: except sqlalchemy.exc.SQLAlchemyError as e:
print 'Could not store product %s: %s' % (name, e) print('Could not store product %s: %s' % (name, e))
self.pause() self.pause()
@ -108,16 +108,16 @@ class EditProductMenu(Menu):
elif what == 'store': elif what == 'store':
try: try:
self.session.commit() self.session.commit()
print 'Product %s stored' % product.name print('Product %s stored' % product.name)
except sqlalchemy.exc.SQLAlchemyError, e: except sqlalchemy.exc.SQLAlchemyError as e:
print 'Could not store product %s: %s' % (product.name, e) print('Could not store product %s: %s' % (product.name, e))
self.pause() self.pause()
return return
elif what is None: elif what is None:
print 'Edit aborted' print('Edit aborted')
return return
else: else:
print 'What what?' print('What what?')
class AdjustStockMenu(Menu): class AdjustStockMenu(Menu):
@ -128,25 +128,25 @@ class AdjustStockMenu(Menu):
self.print_header() self.print_header()
product = self.input_product('Product> ') product = self.input_product('Product> ')
print 'The stock of this product is: %d ' % product.stock print('The stock of this product is: %d ' % product.stock)
print 'Write the number of products you have added to the stock' print('Write the number of products you have added to the stock')
print 'Alternatively, correct the stock for any mistakes' print('Alternatively, correct the stock for any mistakes')
add_stock = self.input_int('Added stock> ', (-1000, 1000)) add_stock = self.input_int('Added stock> ', (-1000, 1000))
print 'You added %d to the stock of %s' % (add_stock, product) print('You added %d to the stock of %s' % (add_stock, product))
product.stock += add_stock product.stock += add_stock
print 'The stock is now %d' % product.stock print('The stock is now %d' % product.stock)
try: try:
self.session.commit() self.session.commit()
print 'Stock is now stored' print('Stock is now stored')
self.pause() self.pause()
except sqlalchemy.exc.SQLAlchemyError, e: except sqlalchemy.exc.SQLAlchemyError as e:
print 'Could not store stock: %s' % e print('Could not store stock: %s' % e)
self.pause() self.pause()
return return
print 'The stock is now %d' % product.stock print('The stock is now %d' % product.stock)
class CleanupStockMenu(Menu): class CleanupStockMenu(Menu):
@ -158,10 +158,10 @@ class CleanupStockMenu(Menu):
products = self.session.query(Product).filter(Product.stock != 0).all() products = self.session.query(Product).filter(Product.stock != 0).all()
print "Every product in stock will be printed." print("Every product in stock will be printed.")
print "Entering no value will keep current stock or set it to 0 if it is negative." print("Entering no value will keep current stock or set it to 0 if it is negative.")
print "Entering a value will set current stock to that value." print("Entering a value will set current stock to that value.")
print "Press enter to begin." print("Press enter to begin.")
self.pause() self.pause()
@ -176,12 +176,12 @@ class CleanupStockMenu(Menu):
try: try:
self.session.commit() self.session.commit()
print 'New stocks are now stored.' print('New stocks are now stored.')
self.pause() self.pause()
except sqlalchemy.exc.SQLAlchemyError, e: except sqlalchemy.exc.SQLAlchemyError as e:
print 'Could not store stock: %s' % e print('Could not store stock: %s' % e)
self.pause() self.pause()
return return
for p in changed_products: for p in changed_products:
print p[0].name, ".", p[1], "->", p[0].stock print(p[0].name, ".", p[1], "->", p[0].stock)

View File

@ -46,7 +46,7 @@ class FAQMenu(Menu):
MessageMenu('Where are the easter eggs? I tried saying "moo", but nothing happened.', MessageMenu('Where are the easter eggs? I tried saying "moo", but nothing happened.',
'Don\'t say "moo".'), 'Don\'t say "moo".'),
MessageMenu('Why does the program speak English when all the users are Norwegians?', MessageMenu('Why does the program speak English when all the users are Norwegians?',
u'Godt spørsmål. Det virket sikkert som en god idé der og da.'), 'Godt spørsmål. Det virket sikkert som en god idé der og da.'),
MessageMenu('I found a bug; is there a reward?', MessageMenu('I found a bug; is there a reward?',
''' '''
No. No.

View File

@ -38,7 +38,7 @@ class Menu(object):
def exit_menu(self): def exit_menu(self):
if self.exit_disallowed_msg is not None: if self.exit_disallowed_msg is not None:
print self.exit_disallowed_msg print(self.exit_disallowed_msg)
return return
if self.exit_confirm_msg is not None: if self.exit_confirm_msg is not None:
if not self.confirm(self.exit_confirm_msg, default=True): if not self.confirm(self.exit_confirm_msg, default=True):
@ -47,27 +47,27 @@ class Menu(object):
def at_exit(self): def at_exit(self):
if self.exit_msg: if self.exit_msg:
print self.exit_msg print(self.exit_msg)
def set_context(self, string, display=True): def set_context(self, string, display=True):
self.context = string self.context = string
if self.context is not None and display: if self.context is not None and display:
print self.context print(self.context)
def add_to_context(self, string): def add_to_context(self, string):
self.context += string self.context += string
def printc(self, string): def printc(self, string):
print string print(string)
if self.context is None: if self.context is None:
self.context = string self.context = string
else: else:
self.context += '\n' + string self.context += '\n' + string
def show_context(self): def show_context(self):
print self.header_format % self.name print(self.header_format % self.name)
if self.context is not None: if self.context is not None:
print self.context print(self.context)
def item_is_submenu(self, i): def item_is_submenu(self, i):
return isinstance(self.items[i], Menu) return isinstance(self.items[i], Menu)
@ -98,7 +98,7 @@ class Menu(object):
if result is None or re.match(regex + '$', result): if result is None or re.match(regex + '$', result):
return result return result
else: else:
print 'Value must match regular expression "%s"' % regex print('Value must match regular expression "%s"' % regex)
if length_range != (None, None): if length_range != (None, None):
while True: while True:
result = self.input_str(prompt, empty_string_is_none=empty_string_is_none) result = self.input_str(prompt, empty_string_is_none=empty_string_is_none)
@ -109,11 +109,11 @@ class Menu(object):
if ((length_range[0] and length < length_range[0]) or if ((length_range[0] and length < length_range[0]) or
(length_range[1] and length > length_range[1])): (length_range[1] and length > length_range[1])):
if length_range[0] and length_range[1]: if length_range[0] and length_range[1]:
print 'Value must have length in range [%d,%d]' % length_range print('Value must have length in range [%d,%d]' % length_range)
elif length_range[0]: elif length_range[0]:
print 'Value must have length at least %d' % length_range[0] print('Value must have length at least %d' % length_range[0])
else: else:
print 'Value must have length at most %d' % length_range[1] print('Value must have length at most %d' % length_range[1])
else: else:
return result return result
while True: while True:
@ -129,11 +129,11 @@ class Menu(object):
# timeout occurred, simulate empty line # timeout occurred, simulate empty line
result = '' result = ''
else: else:
result = unicode(raw_input(), conf.input_encoding).strip() result = str(input(), conf.input_encoding).strip()
else: else:
result = unicode(raw_input(safe_str(prompt)), conf.input_encoding).strip() result = str(input(safe_str(prompt)), conf.input_encoding).strip()
except EOFError: except EOFError:
print 'quit' print('quit')
self.exit_menu() self.exit_menu()
continue continue
if result in exit_commands: if result in exit_commands:
@ -180,7 +180,7 @@ class Menu(object):
while True: while True:
result = self.input_str(prompt) result = self.input_str(prompt)
if result == '': if result == '':
print 'Please enter something' print('Please enter something')
# 'c' in main menu to change colours # 'c' in main menu to change colours
elif result == 'c': elif result == 'c':
os.system('echo -e "\033[' + str(random.randint(40, 49)) + ';' + str(random.randint(30, 37)) + ';5m"') os.system('echo -e "\033[' + str(random.randint(40, 49)) + ';' + str(random.randint(30, 37)) + ';5m"')
@ -204,7 +204,7 @@ class Menu(object):
self.invalid_menu_choice(result) self.invalid_menu_choice(result)
def invalid_menu_choice(self, in_str): def invalid_menu_choice(self, in_str):
print 'Please enter a valid choice.' print('Please enter a valid choice.')
def input_int(self, prompt=None, allowed_range=(None, None), null_allowed=False, default=None): def input_int(self, prompt=None, allowed_range=(None, None), null_allowed=False, default=None):
if prompt is None: if prompt is None:
@ -223,15 +223,15 @@ class Menu(object):
if ((allowed_range[0] and value < allowed_range[0]) or if ((allowed_range[0] and value < allowed_range[0]) or
(allowed_range[1] and value > allowed_range[1])): (allowed_range[1] and value > allowed_range[1])):
if allowed_range[0] and allowed_range[1]: if allowed_range[0] and allowed_range[1]:
print 'Value must be in range [%d,%d]' % allowed_range print('Value must be in range [%d,%d]' % allowed_range)
elif allowed_range[0]: elif allowed_range[0]:
print 'Value must be at least %d' % allowed_range[0] print('Value must be at least %d' % allowed_range[0])
else: else:
print 'Value must be at most %d' % allowed_range[1] print('Value must be at most %d' % allowed_range[1])
else: else:
return value return value
except ValueError: except ValueError:
print "Please enter an integer" print("Please enter an integer")
def input_user(self, prompt=None): def input_user(self, prompt=None):
user = None user = None
@ -275,7 +275,7 @@ class Menu(object):
num = 1 num = 1
if (result is None) and (len(search_lst) > 1): if (result is None) and (len(search_lst) > 1):
print 'Interpreting input as "<number> <product>"' print('Interpreting input as "<number> <product>"')
try: try:
num = int(search_lst[0]) num = int(search_lst[0])
result = self.search_for_thing(" ".join(search_lst[1:]), permitted_things, add_nonexisting, result = self.search_for_thing(" ".join(search_lst[1:]), permitted_things, add_nonexisting,
@ -321,7 +321,7 @@ class Menu(object):
def search_add(self, string): def search_add(self, string):
type_guess = guess_data_type(string) type_guess = guess_data_type(string)
if type_guess == 'username': if type_guess == 'username':
print '"%s" looks like a username, but no such user exists.' % string print('"%s" looks like a username, but no such user exists.' % string)
if self.confirm('Create user %s?' % string): if self.confirm('Create user %s?' % string):
user = User(string, None) user = User(string, None)
self.session.add(user) self.session.add(user)
@ -342,11 +342,11 @@ class Menu(object):
user = self.input_user('User to set card number for> ') user = self.input_user('User to set card number for> ')
old_card = user.card old_card = user.card
user.card = string user.card = string
print 'Card number of %s set to %s (was %s)' % (user.name, string, old_card) print('Card number of %s set to %s (was %s)' % (user.name, string, old_card))
return user return user
return None return None
if type_guess == 'bar_code': if type_guess == 'bar_code':
print '"%s" looks like the bar code for a product, but no such product exists.' % string print('"%s" looks like the bar code for a product, but no such product exists.' % string)
return None return None
def search_ui(self, search_fun, search_str, thing): def search_ui(self, search_fun, search_str, thing):
@ -357,11 +357,11 @@ class Menu(object):
if not isinstance(result, list): if not isinstance(result, list):
return result return result
if len(result) == 0: if len(result) == 0:
print 'No %ss matching "%s"' % (thing, search_str) print('No %ss matching "%s"' % (thing, search_str))
return None return None
if len(result) == 1: if len(result) == 1:
msg = 'One %s matching "%s": %s. Use this?' % \ msg = 'One %s matching "%s": %s. Use this?' % \
(thing, search_str, unicode(result[0])) (thing, search_str, str(result[0]))
if self.confirm(msg, default=True): if self.confirm(msg, default=True):
return result[0] return result[0]
return None return None
@ -383,15 +383,15 @@ class Menu(object):
return ConfirmMenu(prompt, default, timeout).execute() return ConfirmMenu(prompt, default, timeout).execute()
def print_header(self): def print_header(self):
print "" print("")
print self.header_format % self.name print(self.header_format % self.name)
def pause(self): def pause(self):
self.input_str('.') self.input_str('.')
@staticmethod @staticmethod
def general_help(): def general_help():
print ''' print('''
DIBBLER HELP DIBBLER HELP
The following commands are recognized (almost) everywhere: The following commands are recognized (almost) everywhere:
@ -412,15 +412,15 @@ class Menu(object):
of money PVVVV owes the user. This value decreases with the of money PVVVV owes the user. This value decreases with the
appropriate amount when you register a purchase, and you may increase appropriate amount when you register a purchase, and you may increase
it by putting money in the box and using the "Adjust credit" menu. it by putting money in the box and using the "Adjust credit" menu.
''' ''')
def local_help(self): def local_help(self):
if self.help_text is None: if self.help_text is None:
print 'no help here' print('no help here')
else: else:
print '' print('')
print 'Help for %s:' % (self.header_format % self.name) print('Help for %s:' % (self.header_format % self.name))
print self.help_text print(self.help_text)
def execute(self, **kwargs): def execute(self, **kwargs):
self.set_context(None) self.set_context(None)
@ -462,8 +462,8 @@ class MessageMenu(Menu):
def _execute(self): def _execute(self):
self.print_header() self.print_header()
print '' print('')
print self.message print(self.message)
if self.pause_after_message: if self.pause_after_message:
self.pause() self.pause()
@ -487,7 +487,7 @@ class ConfirmMenu(Menu):
elif self.default is not None and result == '': elif self.default is not None and result == '':
return self.default return self.default
else: else:
print 'Please answer yes or no' print('Please answer yes or no')
class Selector(Menu): class Selector(Menu):
@ -499,13 +499,13 @@ class Selector(Menu):
self.header_format = '%s' self.header_format = '%s'
def print_header(self): def print_header(self):
print self.header_format % self.name print(self.header_format % self.name)
def local_help(self): def local_help(self):
if self.help_text is None: if self.help_text is None:
print 'This is a selection menu. Enter one of the listed numbers, or' print('This is a selection menu. Enter one of the listed numbers, or')
print '\'exit\' to go out and do something else.' print('\'exit\' to go out and do something else.')
else: else:
print '' print('')
print 'Help for selector (%s):' % self.name print('Help for selector (%s):' % self.name)
print self.help_text print(self.help_text)

View File

@ -46,4 +46,4 @@ class MainMenu(Menu):
return False return False
def invalid_menu_choice(self, in_str): def invalid_menu_choice(self, in_str):
print self.show_context() print(self.show_context())

View File

@ -31,12 +31,12 @@ class TransferMenu(Menu):
self.session.add(t2) self.session.add(t2)
try: try:
self.session.commit() self.session.commit()
print 'Transfered %d kr from %s to %s' % (amount, user1, user2) print('Transfered %d kr from %s to %s' % (amount, user1, user2))
print 'User %s\'s credit is now %d kr' % (user1, user1.credit) print('User %s\'s credit is now %d kr' % (user1, user1.credit))
print 'User %s\'s credit is now %d kr' % (user2, user2.credit) print('User %s\'s credit is now %d kr' % (user2, user2.credit))
print 'Comment: %s' % comment print('Comment: %s' % comment)
except sqlalchemy.exc.SQLAlchemyError, e: except sqlalchemy.exc.SQLAlchemyError as e:
print 'Could not perform transfer: %s' % e print('Could not perform transfer: %s' % e)
# self.pause() # self.pause()
@ -47,10 +47,10 @@ class ShowUserMenu(Menu):
def _execute(self): def _execute(self):
self.print_header() self.print_header()
user = self.input_user('User name, card number or RFID> ') user = self.input_user('User name, card number or RFID> ')
print 'User name: %s' % user.name print('User name: %s' % user.name)
print 'Card number: %s' % user.card print('Card number: %s' % user.card)
print 'RFID: %s' % user.rfid print('RFID: %s' % user.rfid)
print 'Credit: %s kr' % user.credit print('Credit: %s kr' % user.credit)
selector = Selector('What do you want to know about %s?' % user.name, selector = Selector('What do you want to know about %s?' % user.name,
items=[('transactions', 'Recent transactions (List of last ' + str( items=[('transactions', 'Recent transactions (List of last ' + str(
conf.user_recent_transaction_limit) + ')'), conf.user_recent_transaction_limit) + ')'),
@ -64,7 +64,7 @@ class ShowUserMenu(Menu):
elif what == 'transactions-all': elif what == 'transactions-all':
self.print_all_transactions(user) self.print_all_transactions(user)
else: else:
print 'What what?' print('What what?')
@staticmethod @staticmethod
def print_all_transactions(user): def print_all_transactions(user):
@ -77,8 +77,7 @@ class ShowUserMenu(Menu):
abs(t.amount)) abs(t.amount))
if t.purchase: if t.purchase:
string += 'purchase (' string += 'purchase ('
string += ', '.join(map(lambda e: e.product.name, string += ', '.join([e.product.name for e in t.purchase.entries])
t.purchase.entries))
string += ')' string += ')'
if t.penalty > 1: if t.penalty > 1:
string += ' * %dx penalty applied' % t.penalty string += ' * %dx penalty applied' % t.penalty
@ -101,8 +100,7 @@ class ShowUserMenu(Menu):
abs(t.amount)) abs(t.amount))
if t.purchase: if t.purchase:
string += 'purchase (' string += 'purchase ('
string += ', '.join(map(lambda e: e.product.name, string += ', '.join([e.product.name for e in t.purchase.entries])
t.purchase.entries))
string += ')' string += ')'
if t.penalty > 1: if t.penalty > 1:
string += ' * %dx penalty applied' % t.penalty string += ' * %dx penalty applied' % t.penalty
@ -121,12 +119,12 @@ class ShowUserMenu(Menu):
products.append((product, count)) products.append((product, count))
num_products = len(products) num_products = len(products)
if num_products == 0: if num_products == 0:
print 'No products purchased yet' print('No products purchased yet')
else: else:
text = '' text = ''
text += 'Products purchased:\n' text += 'Products purchased:\n'
for product, count in products: for product, count in products:
text += u'{0:<47} {1:>3}\n'.format(product.name, count) text += '{0:<47} {1:>3}\n'.format(product.name, count)
less(text) less(text)
@ -158,15 +156,15 @@ class AdjustCreditMenu(Menu): # reimplements ChargeMenu; these should be combin
def _execute(self): def _execute(self):
self.print_header() self.print_header()
user = self.input_user('User> ') user = self.input_user('User> ')
print 'User %s\'s credit is %d kr' % (user.name, user.credit) print('User %s\'s credit is %d kr' % (user.name, user.credit))
self.set_context('Adjusting credit for user %s' % user.name, display=False) self.set_context('Adjusting credit for user %s' % user.name, display=False)
print '(Note on sign convention: Enter a positive amount here if you have' print('(Note on sign convention: Enter a positive amount here if you have')
print 'added money to the PVVVV money box, a negative amount if you have' print('added money to the PVVVV money box, a negative amount if you have')
print 'taken money from it)' print('taken money from it)')
amount = self.input_int('Add amount> ', (-100000, 100000)) amount = self.input_int('Add amount> ', (-100000, 100000))
print '(The "log message" will show up in the transaction history in the' print('(The "log message" will show up in the transaction history in the')
print '"Show user" menu. It is not necessary to enter a message, but it' print('"Show user" menu. It is not necessary to enter a message, but it')
print 'might be useful to help you remember why you adjusted the credit)' print('might be useful to help you remember why you adjusted the credit)')
description = self.input_str('Log message> ', length_range=(0, 50)) description = self.input_str('Log message> ', length_range=(0, 50))
if description == '': if description == '':
description = 'manually adjusted credit' description = 'manually adjusted credit'
@ -175,9 +173,9 @@ class AdjustCreditMenu(Menu): # reimplements ChargeMenu; these should be combin
self.session.add(transaction) self.session.add(transaction)
try: try:
self.session.commit() self.session.commit()
print 'User %s\'s credit is now %d kr' % (user.name, user.credit) print('User %s\'s credit is now %d kr' % (user.name, user.credit))
except sqlalchemy.exc.SQLAlchemyError, e: except sqlalchemy.exc.SQLAlchemyError as e:
print 'Could not store transaction: %s' % e print('Could not store transaction: %s' % e)
# self.pause() # self.pause()
@ -210,7 +208,7 @@ class ProductSearchMenu(Menu):
self.print_header() self.print_header()
self.set_context('Enter (part of) product name or bar code') self.set_context('Enter (part of) product name or bar code')
product = self.input_product() product = self.input_product()
print 'Result: %s, price: %d kr, bar code: %s, stock: %d, hidden: %s' % (product.name, product.price, print('Result: %s, price: %d kr, bar code: %s, stock: %d, hidden: %s' % (product.name, product.price,
product.bar_code, product.stock, product.bar_code, product.stock,
("Y" if product.hidden else "N")) ("Y" if product.hidden else "N")))
# self.pause() # self.pause()

View File

@ -27,7 +27,7 @@ class ProductPopularityMenu(Menu):
.order_by(desc(sub.c.purchase_count)) \ .order_by(desc(sub.c.purchase_count)) \
.filter(sub.c.purchase_count is not None) \ .filter(sub.c.purchase_count is not None) \
.all() .all()
line_format = u'{0:10s} | {1:>45s}\n' line_format = '{0:10s} | {1:>45s}\n'
text += line_format.format('items sold', 'product') text += line_format.format('items sold', 'product')
text += '-' * (31 + Product.name_length) + '\n' text += '-' * (31 + Product.name_length) + '\n'
for product, number in product_list: for product, number in product_list:
@ -55,7 +55,7 @@ class ProductRevenueMenu(Menu):
.order_by(desc(sub.c.purchase_count * Product.price)) \ .order_by(desc(sub.c.purchase_count * Product.price)) \
.filter(sub.c.purchase_count is not None) \ .filter(sub.c.purchase_count is not None) \
.all() .all()
line_format = u'{0:7s} | {1:10s} | {2:6s} | {3:>45s}\n' line_format = '{0:7s} | {1:10s} | {2:6s} | {3:>45s}\n'
text += line_format.format('revenue', 'items sold', 'price', 'product') text += line_format.format('revenue', 'items sold', 'price', 'product')
text += '-' * (31 + Product.name_length) + '\n' text += '-' * (31 + Product.name_length) + '\n'
for product, number in product_list: for product, number in product_list:

2
ui.py
View File

@ -178,7 +178,7 @@ class ChargeMenu(SubMenu):
def textpad_edit(self, ch): def textpad_edit(self, ch):
self.textpad.do_command(ch) self.textpad.do_command(ch)
self.search_text = self.textpad.gather().strip() self.search_text = self.textpad.gather().strip()
self.resultview.set_list(self.session.query(User).filter(or_(User.user.like(unicode('%'+self.search_text+'%')),User.id.like('%'+self.search_text+'%'))).all()) self.resultview.set_list(self.session.query(User).filter(or_(User.user.like(str('%'+self.search_text+'%')),User.id.like('%'+self.search_text+'%'))).all())
# self.resultview.draw() # self.resultview.draw()
# self.resultwindow.refresh() # self.resultwindow.refresh()

View File

@ -18,8 +18,7 @@ def write_log(f):
transaction_list = session.query(Transaction).all() transaction_list = session.query(Transaction).all()
for transaction in transaction_list: for transaction in transaction_list:
if transaction.purchase: if transaction.purchase:
products = ', '.join(map(lambda ent: ent.product.name, products = ', '.join([ent.product.name for ent in transaction.purchase.entries])
transaction.purchase.entries))
description = '' description = ''
else: else:
products = '' products = ''
@ -33,6 +32,6 @@ if len(sys.argv) < 2:
write_log(sys.stdout) write_log(sys.stdout)
else: else:
filename = sys.argv[1] filename = sys.argv[1]
print 'Writing log to ' + filename print('Writing log to ' + filename)
with open(filename, 'w') as f: with open(filename, 'w') as f:
write_log(f) write_log(f)