Any idea what's wrong with my code on python? - python

ihave this code
import serial
import time
import datetime
import MySQLdb as mdb
localtime = time.localtime(time.time())
port = serial.Serial("/dev/ttyUSB0", baudrate=9600)
count = 0
nomor =''
start = '\x02'
stop = '\x03'
def mulai():
print "Silahkan tempel kartu anda"
def no_dosen()
print "Dosen tidak terdaftar"
mulai()
def no_jadwal()
print "Tidak ada jadwal kuliah"
mulai()
def ada_dosen(dosen)
print dosen
return
def ada_matkul(matkul)
print matkul
return
def cek_dosen(no)
db = mdb.connect("localhost", "azis48", "azis48", "skripsi")
cur = db.cursor()
cond1 = "SELECT * FROM dosen WHERE kode_dosen = %s" %(no)
try:
cur.execute(cond1)
hitung = cur.rowcount
res1 = cur.fetchall()
for row in res1:
nama_dosen = row[1]
if hitung == 1:
return nama_dosen
elif hitung != 1:
return 'null'
except:
db.close()
def cek_jadwal(day,time)
db = mdb.connect("localhost", "azis48", "azis48", "skripsi")
cur = db.cursor()
cond2 = "SELECT nama_mk FROM jadwal WHERE hari = '%s' AND waktu = '%s'" %(day,time)
try:
cur.execute(cond2)
hitung = cur.rowcount
res2 = cur.fetchall()
for row in res2:
nama_mk = row[1]
if hitung == 1:
return nama_mk
elif hitung != 1:
return 'null'
except:
db.close()
def cek_pertemuan(matkul)
db = mdb.connect("localhost", "azis48", "azis48", "skripsi")
cur = db.cursor()
cond3 = "SELECT pertemuan_ke FROM acara WHERE nama_mk = '%s'" %(matkul)
try:
cur.execute(cond3)
res3 = cur.fetchall()
for row in res3:
pertemuan_ke = row[0]
return pertemuan_ke
except:
db.close()
def base()
day = localtime.tm_wday
time = localtime.tm_hour
no = str(nomor)
dosen = cek_dosen(no)
if dosen == 'null':
no_dosen()
elif dosen != 'null':
ada_dosen()
matkul = cek_jadwal(day,time)
if matkul == 'null':
no_jadwal()
elif matkul != 'null':
ada_matkul()
pertemuan = cek_pertemuan(matkul)
print pertemuan
mulai()
if __name__ == '__main__':
mulai()
while True:
data = port.read()
count += 1
if count == 1:
if str(data) != start:
nomor = ''
count = 0
elif 2 <= count <= 13:
nomor = nomor + str(data)
elif count == 16 and str(data) == stop:
base(nomor)
nomor = ''
count = 0
everytime i run this code, its only print the ada_dosen function from all in def base(), if i stop it with ctrl+c here is the traceback
DOSEN3
Traceback(most recent call last):
file "skripsi.py", line 111, in<module>
base(nomor)
any ide what wrong so all function on my def base() running?

There are some issues in your code, to highlight a few -
All your functions are defined as def <function name>() , you do not have an ending : , without that you should most probably be getting syntax errors.
You have defined your base function as def base() , but in your main part of the program, you are trying to call it by passing an argument nomor as base(nomor) , I think you need to change the function defnition to accept the argument as - def base(nomor):

Related

loop instance method with list elements

I am trying to write a program (API testing) to loop through instance methods in a class. One of the methods "get_one_sale_license" has a variable "self.sale_sgid_in_test" I need to assign this variable each element in the list "sale_list_final" .The variable is used in the instance method as well as the main function. I put a for loop outside the class and it works fine with the output( this is modified part of a single file from the application using framework).
However, I want to remove the loop wrapping the class and try in a more pythonic way.
import json
from datetime import *
from N import NSession
from N import NArgParser
from i_data_provider import iDataProvider
sale_list = open("sales.txt").readlines()
sale_list_final = [s.rstrip() for s in sale_list]
tests_list = open("tests.txt").readlines()
tests_list_final = [t.rstrip() for t in tests_list]
cnt=0
cnt2=0
cnt3=0
cnt6=0
cnt11=0
for i in sale_list_final:
class iDeployChecks:
def __init__(self, badge, environment):
self.session = NSession(badge=badge,environment=environment)
self.logger = self.session.logger
# self.sale_sgid_list = []
self.sale_sgid_in_test = ''
self.i_session = iDataProvider(self.session)
def get_all_saleable_sales(self):
global cnt2
if cnt2 == 0:
self.i_session.get_sale_seller_info()
self.logger.info('SUCCESS..... Get all sales api\n')
cnt2 += 1
def get_all_sale_dashboard(self):
global cnt6
if cnt6 == 0:
self.i_session.get_All_sale()
self.logger.info('SUCCESS..... Get all sales on dashboard api\n')
cnt6 += 1
def get_current_user_sale_dashboard(self):
global cnt11
if cnt11 == 0:
self.i_session.get_current_user_sale()
self.logger.info('SUCCESS..... Get current sales on dashboard api\n')
cnt11 += 1
def get_one_sale_license(self):
self.logger.info('Getting sale details from:')
self.sale_sgid_list1 = [item.get('salesgid') for item in self.i_session.get_sale_seller_info()]
#self.sale_sgid_list =[item.get('salesgid') for item in self.i_session.get_sale_seller_info() if item.get('salesgid') == i]
print " for sale " + str(i)
self.sale_sgid_in_test = ''.join(i)
self.logger.info('\n')
self.logger.info('Get License for sale with sale sgid {}'.format(self.sale_sgid_in_test))
self.i_session.get_sale_license(self.sale_sgid_in_test)
self.logger.info('SUCCESS..... Get license api\n')
def get_weekly_stats_count(self):
global cnt
if cnt == 0:
self.i_session.get_weekly_statistics()
self.logger.info('SUCCESS..... Weekly statistics api\n')
cnt += 1
def get_sconfig_value_count(self):
self.i_session.get_sconfig_value(self.sale_sgid_in_test)
self.logger.info('SUCCESS..... sconfig api\n')
def main(self):
start = datetime.utcnow()
# check if the method in the list is present in the class, if yes run it.
for j in tests_list_final:
k = "self." + j + "()"
l= [x.strip() for x in j.split(',')]
m= "self."+l[0]+"(self,year)"
n= "self."+l[0]+"(self,year,month)"
if k == str("self.get_all_saleable_sales()"):
if cnt2 == 0:
self.logger.info('Get All sales')
self.get_all_saleable_sales()
self.logger.info('checking if sale with GSID ' + i + ' exists')
if i not in str(self.i_session.get_sale_seller_info()):
print "the sale with GSID " + i + " does not exist !!"
end1 = datetime.utcnow()
self.logger.info('i health check completed in {} seconds.'.format((end1 - start).seconds))
return
else:
print "sale exists !!"
continue
elif k == str("self.get_one_sale_license()"):
self.get_one_sale_license()
continue
elif k == str("self.get_sale_node_status_value()"):
try:
self.logger.info('Get sale node status for sale sgid {}'.format(self.sale_sgid_in_test))
self.get_sale_node_status_value()
except Exception as e: print e
else:
global cnt3
if (cnt3==0):
print '\n'
print " The testcase " +k + "test does not exist,please recheck test name !!"
print '\n'
cnt3 +=1
end = datetime.utcnow()
self.logger.info('IBDL health check completed in {} seconds.'.format((end - start).seconds))
if __name__ == '__main__':
parser = NArgParser(description='i Checks')
args = parser.parse_args()
iDeployChecks(args.badge, args.environment).main()
Remove the loop and include in the init
def __init__(self, badge, environment):
self.session = NSession(badge=badge,environment=environment)
self.logger = self.session.logger
self.sale_sgid_list = [i for i in sale_list_final]
self.sale_sgid_in_test = ''
self.i_session = iDataProvider(self.session)
Then loop for the same list element while calling the main
if __name__ == '__main__':
parser = NArgParser(description='i Checks')
args = parser.parse_args()
for i in sale_sgid_list:
iDeployChecks(args.badge, args.environment,i).main()

How to count elapsed time on Python

I have the following code:
def base(nomor)
day = localtime.tm_wday
time = localtime.tm_hour
no = str(nomor)
dosen = cek_dosen(no)
if dosen == 'null':
no_dosen()
elif dosen != 'null':
ada_dosen()
matkul = cek_jadwal(day,time,dosen)
if matkul == 'null':
no_jadwal()
elif matkul != 'null':
ada_jadwal()
pertemuan = cek_pertemuan(matkul)
print pertemuan
if pertemuan > 1:
cek_before(pertemuan)
filename = ''.join([dosen, matkul, str(pertemuan), ".pptx"])
else:
filename = ''.join([dosen, matkul, str(pertemuan), ".pptx"])
grabfile(filename)
os.system(''.join(["loimpress ",filename]))
pertemuan = pertemuan + 1
update_pertemuan(pertemuan,matkul)
mulai()
if __name__ == '__main__':
mulai()
while True:
data = port.read()
count += 1
if count == 1:
if str(data) != start:
nomor = ''
count = 0
elif 2 <= count <= 13:
nomor = nomor + str(data)
elif count == 16 and str(data) == stop:
base(nomor)
nomor = ''
count = 0
I want to count time elapse from after data = port.read() until after grabfile(filename). I've used start = time.time() after data = port.read and end = time.time() after grabfile, time = end - start, but it stuck after data = port.read() so I use Ctrl + C to stop that. If I put start = time.time() after no = str(nomor), I get Attribute Error : 'int' object has no attribute 'time'.
How do I count the elapsed time?
from time import clock
start = clock()
...
print "Time taken = %.5f" % (clock() - start)
Summarized:
import datetime
if __name__ == "__main__":
d1 = datetime.datetime.now()
data = port.read()
# Do more things ...
tdelta = datetime.datetime.now() - d1
print(tdelta.total_seconds()) # This is your answer
Take a look at the python timeit module.
Basic example:
>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

How to make a ping client in Python socket?

I learn Python and as a practice decided to write a server for a network game "Backgammon". The question arose as to make sure that found in the queue apponet still online? How to send a ping and accept the answer? I'm trying to do it on line 71, but this is incorrect.
import pymongo, socket, threading, string, json, MySQLdb, random, time
stat = True
conn = {}
#gamers = {}
games = {}
diceroll = []
tempconn = {}
c = pymongo.Connection()
db = c.nardy
nru = db.notregusers
uwait = db.userwait
class ClientThread(threading.Thread):
def __init__(self, channel, details):
self.channel = channel
self.details = details
threading.Thread.__init__(self)
def getUserId(self, data):
json_data = json.loads(data)
if json_data['t'] == 'n':
print ' - User not register'
if nru.find({'identuser':json_data['i'], 'platform':json_data['p']}).count() == 0:
print ' - New user'
count = nru.find().count();
newid = count + 1;
nru.save({'id':newid, 'identuser':json_data['i'], 'platform':json_data['p'], 'level':1})
return nru.find_one({'id':newid})
else:
print ' - Old user'
return nru.find_one({'identuser':json_data['i'], 'platform':json_data['p']})
elif json_data['t'] == 'r':
return 9999
def mySQLConnect(self):
db = MySQLdb.connect(host="localhost", user="", passwd="", db="", charset='utf8')
return db
def run(self):
while True:
data = self.channel.recv(1024)
try:
json_data = json.loads(data)
comm = json_data['c']
if comm == 'x':
if conn.has_key(gamer['level']) and self in conn[gamer['level']]:
conn[gamer['level']].remove(self)
self.channel.close()
break
elif comm == 'h':
gamer = self.getUserId(data)
self.gamer = gamer
elif comm == 'f':
lev = 0
findenemy = 1
while findenemy == 1:
if conn.has_key(gamer['level']):
lev = gamer['level']
elif conn.has_key((gamer['level'] - 1)):
lev = (gamer['level'] - 1)
elif conn.has_key((gamer['level'] + 1)):
lev = (gamer['level'] + 1)
if lev != 0:
if len(conn[lev]) > 0:
enemy = conn[lev].pop(0)
firsttime = time.time()
enemy.channel.send('{"o":"p"}')
while (firsttime + 30) > time.time() and findenemy == 1:
if comm == 'k':
findenemy = 0
print ' - Ping enemy: ok'
if findenemy == 0:
self.enemy = enemy
gameid = str(self.gamer['id']) + '_' + str(self.enemy.gamer['id'])
games[gameid] = {'dice':[], 'nextstep':0}
vrag = self.enemy
a = random.sample(range(1,7),2)
self.channel.send('{"o":"s", "u":"' + str(a[0]) + '", "e":"' + str(a[1]) + '"}')
vrag.channel.send('{"o":"s", "u":"' + str(a[1]) + '", "e":"' + str(a[0]) + '"}')
if a[0] > a[1]:
step = 1
games[gameid]['nextstep'] = self.gamer['id']
self.channel.send('{"o":"u"}')
vrag.channel.send('{"o":"w"}')
else:
step = 2
games[gameid]['nextstep'] = self.enemy.gamer['id']
self.channel.send('{"o":"w"}')
vrag.channel.send('{"o":"u"}')
tempconn[self.enemy] = self
else:
conn[lev].append(self)
findenemy = 0
self.channel.send('{"o":"q"}')
else:
conn[gamer['level']] = [self]
self.channel.send('{"o":"q"}')
elif comm == 'w':
if not hasattr(self, 'enemy'):
self.enemy = tempconn[self]
vrag = self.enemy
gameid = str(self.enemy.gamer['id']) + '_' + str(self.gamer['id'])
self.channel.send('{"o":"o"}')
elif comm == 'r' and games[gameid]['nextstep'] == self.gamer['id']:
dice = []
dice.append(self.gamer['id'])
dice.append(random.randint(1,6))
dice.append(random.randint(1,6))
games[gameid]['dice'].append(dice)
self.channel.send('{"o":"r", "f":"' + str(dice[1]) + '", "s":"' + str(dice[2]) + '"}')
vrag.channel.send('{"o":"r", "f":"' + str(dice[1]) + '", "s":"' + str(dice[2]) + '"}')
games[gameid]['nextstep'] = self.enemy.gamer['id']
elif comm == 'r' and games[gameid]['nextstep'] != self.gamer['id']:
self.channel.send('{"o":"w"}')
elif comm == 'm' and 't' in json_data:
self.channel.send('{"o":"y", "t":"' + str(json_data['text']) + '"}')
vrag.channel.send('{"o":"e", "t":"' + str(json_data['text']) + '"}')
elif comm == 's':
self.channel.send('{"o":"g", "countgame":"' + str(len(games)) + '"}')
elif comm == 'q' and 's' in json_data and 'e' in json_data:
print " - Player step"
elif comm == 'b' and self in conn[gamer['level']]:
conn[gamer['level']].remove(self)
except ValueError:
continue
print 'Closed connection:', self.details[0]
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 8088))
server.listen(5)
while stat:
channel, details = server.accept()
ClientThread(channel, details).start()
Perhaps, in addition to answering the question, you give me some recommendations ...
There are two options for you to send out a ping and get response.
Use scapy. Use sendp function to send a ping and get response.
Use os.system to invoke command line to send a ping and get response. Like os.system('ping 127.0.0.1')
Hope it helps.:)

'raw_input' does nothing, regardless of the input given

I am trying to make a tool that will encode/decode a string according to values in a dictionary however, I am stuck with the following code:
class edt():
e_dic = {}
def main(self):
c = "hcqnxmytwukgirzoeaspdfvlbj"
a = "abcdefghijklmnopqrstuvwxyz"
e_dic = {}
for i in range(len(c)):
e_dic[a[i]] = c[i]
e_dic[" "] = " "
self.e_dic = e_dic
e = edt()
user_input = raw_input("1.Encode\n2.Decode\n")
if user_input == "1":
e.encode()
elif user_input == "2":
e.decode()
else:
False
def encode(self):
print("test")
def decode(self):
print("test")
def run():
run_main = None
run_main = edt()
run_main.main()
I have omitted encode() and decode() as I don't think that they are causing the problem.
The problem is that this happens when I run it:
>>run()
1.Encode
2.Decode
>>
(The script pauses here to wait for the return key to be pressed, but does nothing regardless of the input given)
>>
I am given no error after this completes. Any help would be greatly appreciated
The code looks fine. But shouldn't you be using an object to call the method? like so
class edt():
e_dic = {}
def encode(self):
print "encoded "
def decode(self):
print "decoded "
def main(self):
c = "hcqnxmytwukgirzoeaspdfvlbj"
a = "abcdefghijklmnopqrstuvwxyz"
e_dic = {}
for i in range(len(c)):
e_dic[a[i]] = c[i]
e_dic[" "] = " "
self.e_dic = e_dic
e = edt()
user_input = raw_input("1.Encode\n2.Decode\n")
if user_input == "1":
e.encode()
elif user_input == "2":
e.decode()
else:
False
def run():
run_main = None
run_main = edt()
run_main.main()
Output:
>>> run()
1.Encode
2.Decode
1
encoded
Fiddle here:
http://ideone.com/9eET4T
You need to use self in encode and decode.
class edt(object):
def __init__(self):
self.e_dic = {}
def main(self):
c = "hcqnxmytwukgirzoeaspdfvlbj"
a = "abcdefghijklmnopqrstuvwxyz"
for i in range(len(c)):
self.e_dic[a[i]] = c[i]
self.e_dic[" "] = " "
user_input = raw_input("1.Encode\n2.Decode\n")
if user_input == "1":
self.encode()
elif user_input == "2":
self.decode()
else:
return False
def encode(self):
print("test")
def decode(self):
print("test")
def run():
run_main = None
run_main = edt()
run_main.main()
run()

python Synchronized Value to be returned is being updated by subsequent code before being returned

I have written the code below to handle and collect perfomance counters (including the test lines (at the end of the code)).
However, when I call the function getAndReset(), it seems to reset the values to Zero before outputting the current value of lendingStats dictionary. This is despite the fact that within the function getAndReset() , the lendingStats value is updated first then stored in a variable theStats.
#!/usr/bin/python
import threading
import time, datetime,pytz
startTime = datetime.datetime.now(pytz.timezone('Africa/Nairobi')).strftime('%Y-%m-%d %H:%M:%S%z')
lendingStats = {'ussdRequests':{'getSubInfo':None,'loanRequests':None},'time':{'startTime':startTime,'currentTime':startTime,'last-reset-time:':startTime}}
lendingStatsNow = {'ussdRequests':{'getSubInfo':None,'loanRequests':None},'time':{'startTime':startTime,'currentTime':startTime,'last-reset-time:':startTime}}
subInfoCounter = dict()
loanRequestCounter = dict()
currentTime = startTime
lastResetTime = startTime
def synchronized(func):
func.__lock__ = threading.RLock()
def synced_func(*args, **kws):
with func.__lock__:
return func(*args, **kws)
return synced_func
#synchronized
def lastResetTimeFunc(action):
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
if action == "Get":
return lastResetTime
elif action == "Update":
lastResetTime = datetime.datetime.now(pytz.timezone('Africa/Nairobi')).strftime('%Y-%m-%d %H:%M:%S%z')
##synchronized
def getAndReset():
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
# Get the values to return
theStats = dict()
theStats = getLendingStats()
resetStats()
return theStats
#synchronized
def resetStats():
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
ussdSubInfoStatsFunc(action="Reset")
ussdLoanReqStatsFunc(action="Reset")
lastResetTimeFunc("Update")
#synchronized
def getLendingStats():
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
# Get the values
# lendingStats['ussdRequests']['getSubInfo'] = ussdSubInfoStatsFunc(action="Get")
# lendingStats['ussdRequests']['loanRequests'] = ussdLoanReqStatsFunc(action="Get")
# lendingStats['time']['last-reset-time'] = lastResetTimeFunc("Get")
# lendingStats['time']['currentTime'] = getCurrentTimeFunc()
returnValue = dict()
for KeyName in lendingStats.iterkeys():
returnValue[KeyName] = dict()
returnValue['ussdRequests']['getSubInfo'] = ussdSubInfoStatsFunc(action="Get")
returnValue['ussdRequests']['loanRequests'] = ussdLoanReqStatsFunc(action="Get")
returnValue['time']['last-reset-time'] = lastResetTimeFunc("Get")
returnValue['time']['currentTime'] = getCurrentTimeFunc()
returnValue['time']['startTime'] = lendingStats['time']['startTime']
lendingStats = returnValue
# Return the Values
return returnValue
#synchronized
def getCurrentTimeFunc():
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
currentTime = datetime.datetime.now(pytz.timezone('Africa/Nairobi')).strftime('%Y-%m-%d %H:%M:%S%z')
theTime = currentTime
return theTime
#synchronized
def ussdLoanReqStatsFunc(**kwargs):
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
if kwargs['action'] == "Add":
if loanRequestCounter.has_key(kwargs['respcode']):
if loanRequestCounter[kwargs['respcode']].has_key(kwargs['denom']):
currentcount = loanRequestCounter[kwargs['respcode']][kwargs['denom']]
loanRequestCounter[kwargs['respcode']][kwargs['denom']] = currentcount + 1
else:
loanRequestCounter[kwargs['respcode']][kwargs['denom']] = 1
else:
loanRequestCounter[kwargs['respcode']] = dict()
loanRequestCounter[kwargs['respcode']][kwargs['denom']] = 1
elif kwargs['action'] == "Reset":
for respCodeKeyName in loanRequestCounter.iterkeys():
for denomKeyName in loanRequestCounter[respCodeKeyName].iterkeys():
loanRequestCounter[respCodeKeyName][denomKeyName] = 0
elif kwargs['action'] == "Get":
theDict = loanRequestCounter
return theDict
#synchronized
def ussdSubInfoStatsFunc(**kwargs):
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
if kwargs['action'] == "Add":
if subInfoCounter.has_key(kwargs['respcode']):
currentcount = subInfoCounter[kwargs['respcode']]
subInfoCounter[kwargs['respcode']] = currentcount + 1
else:
subInfoCounter[kwargs['respcode']] = 1
elif kwargs['action'] == "Reset":
for keyname in subInfoCounter.iterkeys():
subInfoCounter[keyname] = 0
elif kwargs['action'] == "Get":
theDict = subInfoCounter
return theDict
def testSubInfoCounter(KeyName,numOfEvents):
i = 0
while i < numOfEvents:
ussdSubInfoStatsFunc(action="Add",respcode=KeyName)
i +=1
print ussdSubInfoStatsFunc(action="Get")
def testLoanReqCounter(respCodeT,theDenom,numOfEvents):
i = 0
while i < numOfEvents:
ussdLoanReqStatsFunc(action="Add",respcode=respCodeT,denom=theDenom)
i +=1
print ussdLoanReqStatsFunc(action="Get")
thread1 = threading.Thread(target = testLoanReqCounter("0","200",7767))
thread2 = threading.Thread(target = testLoanReqCounter("1","1000",55))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print "At the beginning:"
print getLendingStats()
print getAndReset()
testSubInfoCounter("9",7)
testSubInfoCounter("0",7000)
testLoanReqCounter("0","200",7767)
testLoanReqCounter("1","200",33)
testLoanReqCounter("0","1000",3928)
testLoanReqCounter("1","1000",55)
testLoanReqCounter("0","5000",492)
testSubInfoCounter("1",3000)
testSubInfoCounter("3",1000)
testSubInfoCounter("0",7000)
print "Cumulatively:"
print getAndReset()
# print getLendingStats()
# resetStats()
time.sleep(3)
print "After the Reset"
# print getLendingStats()
# resetStats()
print getAndReset()
testLoanReqCounter("0","200",7767)
testLoanReqCounter("1","200",33)
testLoanReqCounter("0","1000",3928)
testLoanReqCounter("1","1000",55)
testLoanReqCounter("0","5000",492)
print getLendingStats()
resetStats()
testSubInfoCounter("1",3230)
testSubInfoCounter("3",1901)
testSubInfoCounter("0",76887)
print getAndReset()
time.sleep(4)
print getAndReset()
# print getLendingStats()
# resetStats()
The problem here is that I needed to use a deepcopy as opposed to a simple assignment (which uses a simple copy).
Therefore the code that I needed to change was:
import copy
#synchronized
def getAndReset():
global lendingStats,subInfoCounter,loanRequestCounter,currentTime,lastResetTime
# Get the values to return
theStats = copy.deepcopy(getLendingStats())
resetStats()
return theStats

Categories

Resources