Why does the code stop executing after this function call? - python

Here's the primary codeblock.
variables = ['V1','V2','V3',...]
caseList = ['C1','C2','C3',...]
exp = {}
conv = {}
result = {}
for case in caseList:
if case != "Processed":
load_case(case, dirPath, fileTyp)
import_rawData(fileTyp)
convert_units()
display('Hello')
merge_Data(case)
display('Hello')
Here's the output of that codeblock. Nothing executes after the merge_Data() function call.
'Case loaded'
'Raw data imported'
'Units converted'
'Hello'
'Data filtered'
'Data merged'
Here is the code for the merge_Data, and associated filter_expData functions:
def merge_Data(case):
fexpData = filter_expData(case)
for var in variables:
exists = fexpData.get(var,"")
if len(exists) > 0:
temp = conv[var]
temp[var,temp[var].columns[1].replace('Simulation','Experiment')] = pd.Series(fexpData[var].tolist())
temp[var,'Absolute Error'] = abs(temp[var,temp[var].columns[1]] - temp[var,temp[var].columns[2]])
temp[var,'Percentage Error'] = temp[var,temp[var].columns[3]] / temp[var,temp[var].columns[2]] * 100
result[var] = temp
else:
result[var] = conv[var]
display('Data merged')
def filter_expData(case):
var = next(iter(conv))
timeList = pd.Series(conv[var].iloc[:,conv[var].columns.get_level_values(1)=="Time (min)"].iloc[:,0].round(3))
filtExp = exp[case][exp[case]['Time (min)'].round(3).isin(timeList)]
display('Data filtered')
return filtExp
Can you help me understand why code isn't executing after the merge_Data() function call?

Related

Output more than one excel/csv file from a class. OOP. Class Inheritance

I am getting a AttributeError as follows:
self.filtered_df.to_excel(self.output_filepath, index=False)
AttributeError: 'tuple' object has no attribute 'to_excel'
I am inheriting a class for another class I am developing, currently the inheritance allows me to output one excel file, can I change the method in this class to allow me to output more than one excel file in the new class I am developing?
Here is the class, inherited:
class ReportQueryCommand(LogCommand):
"""Performs reports through a ReportQueryStrategy instance.
It is possible to overwrite existing queries; this means that it is possible
to perform subsequent filters by launching multiple commands having
key_input = strategy.name.
Attributes:
state: DatasetState containing so-far computed DataFrames.
strategy: defines how to perform the query.
filepath: optional. Defines where to save the queried DataFrame.
key_input: optional (None if df_to_filter is not None).
Defines a key that allows to access a DataFrame in the State.
df_to_filter: optional (None if key is not None).
DataFrame to apply the query on.
"""
def __init__(self,
strategy: ReportQueryStrategy,
base_path: Optional[str] = None,
key_input: Optional[str] = None,
key_output: Optional[str] = None,
df_to_filter: Optional[pd.DataFrame] = None,
filepath: Optional[str] = None,
directory_path: Optional[str] = None,
write_output: bool = True):
super().__init__(base_path=base_path,
directory_path=directory_path,
copy_before_update=False,
write_output=write_output)
self.state = DatasetState()
self.strategy = strategy
self.filepath = filepath
self.key_input = key_input
self._key_output = key_output
self.df_to_filter = df_to_filter
self.filtered_df = None
#property
def _output_file(self) -> str:
return self.strategy.output_filename
def write_to_file(self):
if self.filtered_df is None:
raise ValueError("Missing computed dataframe")
self.filtered_df.to_excel(self.output_filepath, index=False)
#property
def key_output(self) -> str:
# first scenario: key was defined
if self._key_output is not None:
return self._key_output
# second scenario: key was not defined, by default,
# concatenate key_input and strategy
strategy_output_name = self.strategy.output_name
if self.key_input is not None:
return f"{self.key_input}-{strategy_output_name}"
# WCS: no key defined, just assign the strategy key
return strategy_output_name
def execute(self, output_from_previous: Any = None, **kwargs) -> Any:
self.filtered_df = self.strategy.transform(key=self.key_input,
df=self.df_to_filter)
self.state.query_reports[self.key_output] = self.filtered_df
super().execute(output_from_previous=output_from_previous, **kwargs)
As you can see here the method I need to update is 'def write_to_file(self):'
Here is snippets of the relevant code in development to show where this problems 'could be occuring'. The following bits of code below are relevant, this might need to be updated to allow me to output two excel files or more:
class TtestStrategy(ReportQueryStrategy):
"""
"""
#staticmethod
def _strategy_key():
return 't-test', 'fisher-test'
def __init__(self,
query_name: Optional[str] = None,
reference_query: str = None,
sample_query: str = None,
alpha: float = 0.05,
chemical_key: str = 'chemical',
plate_key: str = 'plate',
value_key: str = 'processed_relative_fp',
group_column: str = 'Lot',
return_pivoted: bool = True):
super().__init__(query_name=query_name)
self.pvalues = []
self.alpha = alpha
self.chemical_key, self.plate_key, self.value_key, self.reference_query, self.sample_query = (chemical_key,
plate_key,
value_key,
reference_query,
sample_query)
self.group_column = group_column
self.return_pivoted = return_pivoted
def fishers_method(self, pvalues) -> tuple[bool, float, float, float]:
pvalues = [item for item in pvalues if not pd.isnull(item)]
comb_z, comb_pval = stats.combine_pvalues(pvalues, method="fisher")
k = len(pvalues)
mean_FDR = (self.alpha * (k + 1)) / (2 * k)
if comb_pval > mean_FDR:
decision = False
else:
decision = True
return decision, comb_z, comb_pval, mean_FDR
def transform(self,
key: Optional[str] = None,
df: Optional[pd.DataFrame] = None) -> tuple[Any, DataFrame]:
counter_nosig = 0
counter_sig_st_t = 0
pval_store_st_t = {}
pval_store_st_t_dec = {}
pval_store_st_t_val = {}
pval_store_st_t_val_adj = {}
pval_store_norm_A = {}
pval_store_norm_B = {}
var_store_A = {}
var_store_B = {}
pval_store_lev_bart = {}
decisions = []
st_pval_arr = []
df = super().transform(key=key, df=df)
df = df.loc[(df[self.group_column] == self.reference_query) | (df[self.group_column] == self.sample_query)]
df_i = df.filter(['plate', 'chemical', 'processed_relative_fp'], axis=1)
df_i = df.pivot(columns='plate', values='processed_relative_fp', index='chemical')
df_i.index.name = None
df_i.columns.name = ''
plates = {exps: {"processed_relative_fp": series}
for exps, series in df_i.to_dict("series").items()}
chem_order = list(df['chemical'].unique())
for chem in chem_order:
if chem != 'empty':
pool = []
sample_l = []
for q in [self.reference_query, self.sample_query]:
sample = pd.Series([sample for sample in plates])
sample = sample[sample.str.contains(q)]
for s in sample:
sample_l.append(s)
record = plates[s]
if record['processed_relative_fp'] is not None:
rel_fp = record['processed_relative_fp']
lot = s.split("_")[1]
cell = s.split('_')[2]
rep = s.split("_")[4]
val = rel_fp[chem]
pool.append({"chems": chem, "lot": lot, "cell": cell, "replicate": rep,
"key": chem + "::" + lot + "::" + rep + "::" + cell, "value": val})
pool = pd.DataFrame(pool)
massage = []
averages = []
sort_lots = list(pool['lot'].unique())
for lot in sort_lots:
value = list(pool[pool.lot.eq(lot)]['value'].dropna())
averages.append(np.mean(np.array(value)))
massage.append(value)
averages = np.array(averages)
min_ = np.nanmin(averages)
max_ = np.nanmax(averages)
pos_min_ = np.where(averages == min_)[0][0]
pos_max_ = np.where(averages == max_)[0][0]
perc_diff = (max_ - min_) * 100
fvalue_st_t, pvalue_st_t = stats.ttest_ind(*massage, equal_var=False)
st_pval_arr.append(pvalue_st_t)
st_pval_array = np.asarray(st_pval_arr)
mask = np.isfinite(st_pval_array)
st_t_t_pval_adj = np.empty(st_pval_array.shape)
st_t_t_pval_adj.fill(np.nan)
rej_st_t, st_t_t_pval_adj[mask], _, _ = sm.stats.multipletests(st_pval_array[mask], method='fdr_bh')
for v in st_t_t_pval_adj:
float(v)
pval_store_st_t_val_adj[chem] = v
for z in rej_st_t:
float(z)
if len(massage[0]) >= 3:
test_stat_norm_A, pvalue_norm_A = stats.shapiro(np.array(massage[0]))
if pvalue_norm_A < 0.05:
pval_store_norm_A[chem] = 'No'
else:
pval_store_norm_A[chem] = 'Yes'
else:
pval_store_norm_A[chem] = 'Not enough data'
if len(massage[1]) >= 3:
test_stat_norm_B, pvalue_norm_B = stats.shapiro(np.array(massage[1]))
if pvalue_norm_B < 0.05:
pval_store_norm_B[chem] = 'No'
else:
pval_store_norm_B[chem] = 'Yes'
else:
pval_store_norm_B[chem] = 'not enough data'
var_stat_A = stats.variation(np.array(massage[0]))
var_stat_B = stats.variation(np.array(massage[1]))
stat_lev_bart, pvalue_lev_bart = stats.levene(*massage, center='mean')
pval_store_st_t[chem] = pvalue_st_t
pval_store_st_t_val[chem] = pvalue_st_t
var_store_A[chem] = var_stat_A
var_store_B[chem] = var_stat_B
pval_store_lev_bart[chem] = pvalue_lev_bart
if pvalue_st_t < 0.05:
pval_store_st_t[chem] = 'diff'
else:
pval_store_st_t[chem] = 'same'
if v > 0.05:
pval_store_st_t_dec[chem] = 'same'
if v < 0.05 and perc_diff > 0.0:
pval_store_st_t_dec[chem] = 'diff'
counter_sig_st_t += 1
else:
counter_nosig += 1
decisions.append(pval_store_st_t)
decisions.append(pval_store_st_t_dec)
decisions.append(pval_store_st_t_val)
decisions.append(pval_store_st_t_val_adj)
decisions.append(pval_store_norm_A)
decisions.append(pval_store_norm_B)
decisions.append(var_store_A)
decisions.append(var_store_B)
decisions.append(pval_store_lev_bart)
decisions = pd.DataFrame(decisions)
decisions = decisions.T
decisions.columns = [
f'Welchs t-test result for lot {self.reference_query} v lot {self.sample_query}',
'Welchs t-test considering Multi-test Correction',
'Welchs t-test pvalue unadjusted',
'Welchs t-test pvalue adjusted',
f'are lot {self.reference_query} chemicals normally distributed?',
f'are lot {self.sample_query} chemicals normally distributed?',
f'lot {self.reference_query} variance',
f'lot {self.sample_query} variance',
'levenes statistic']
decisions_before_filter = decisions.copy()
decisions_before_filter.reset_index(inplace=True)
decisions_before_filter.rename(columns={'index': 'chemicals'}, inplace=True)
decisions = decisions.loc[(decisions['Welchs t-test pvalue adjusted'] < self.alpha)]
decisions.reset_index(inplace=True)
decisions.rename(columns={'index': 'chemicals'}, inplace=True)
decisions.sort_values(by=['Welchs t-test pvalue adjusted'], inplace=True)
decisions_before_filter = decisions_before_filter.filter(items=['chemicals', 'Welchs t-test pvalue adjusted'])
decisions_before_filter = decisions_before_filter.sort_values(by=['Welchs t-test pvalue adjusted'])
results_fishers = self.fishers_method(decisions_before_filter['Welchs t-test pvalue adjusted'].tolist())
results_fishers_df = pd.DataFrame(results_fishers,
index=['decision',
'combined z-score',
'combined p-value',
'meanFDR'])
results_fishers_df = results_fishers_df.T
results_fishers_df['k'] = len(decisions_before_filter.dropna())
results_fishers_df.insert(loc=0, column='comparison', value=(str(self.reference_query + '-' + 'vs'
+ '-' + self.sample_query)))
return decisions, results_fishers_df
See all the information above
The error is telling you that filtered_df is NOT a pandas.DataFrame.
It's a tuple. In fact your TtestStrategy's transform method returns the tuple:
return decisions, results_fishers_df
If you change your code to:
def execute(self, output_from_previous: Any = None, **kwargs) -> Any:
_ignored, self.filtered_df = self.strategy.transform(key=self.key_input,
df=self.df_to_filter)
self.state.query_reports[self.key_output] = self.filtered_df
super().execute(output_from_previous=output_from_previous, **kwargs)
then you shouldn't see that AttributeError anymore.

Why is Flopy giving the same results?

I tried to use flopy, so I could try running some optimization procedures with python and modflow. Modflow requires a number of data to work with and we provide that info using different files.
We provide the input and flopy runs modflow
My trouble is that, flopy seems to disregard the input files and gives the same result, no matter what input I give.
Here's the code:
nper = 10
class BASreader:
def __init__(self):
self.ibound = None
self.head = None
with open("inps/bas/ibound", "r") as f:
data = f.read().replace("-", " -").split()
data = [int(x) for x in data]
data = np.array(data).reshape(1, 71, 24)
self.ibound = data
with open("inps/bas/head", "r") as f:
data = f.read().split()
data = [float(x) for x in data]
self.head = np.array(data).reshape(1, 71, 24)
class Modflow:
def __init__(self):
self.modelname = 'outs/gen1'
self.mf = flopy.modflow.Modflow(self.modelname, exe_name=r'G:\Program Files (x86)\Visual MODFLOW\mf2005.exe')
dis = flopy.modflow.ModflowDis.load("inps/yo.dis", self.mf)
basreader = BASreader()
bas = flopy.modflow.ModflowBas(self.mf, ibound=basreader.ibound, strt=basreader.head)
self.prev_headdata = basreader.head
wel = flopy.modflow.ModflowWel(self.mf, stress_period_data=WellProvider(nper).wells)
fname = 'inps/yo.evt'
fhandle = open(fname, 'r')
packages = []
ext_unit_dict = {22: flopy.utils.mfreadnam.NamData('EVT', fname, fhandle, packages)}
evt = flopy.modflow.ModflowEvt.load(fhandle, self.mf, ext_unit_dict=ext_unit_dict)
fhandle.close()
rech = {}
for x in range(nper):
rech[x] = 1.44e-5
rch = flopy.modflow.ModflowRch(self.mf, rech=rech)
stress_period_data = {}
for kper in range(nper):
for kstp in range(int(nper/10)):
stress_period_data[(kper, kstp)] = ['save head',
'save drawdown',
'save budget',
'print head',
'print drawdown',
'print budget']
oc = flopy.modflow.ModflowOc(self.mf, stress_period_data=stress_period_data, compact=True)
chd = flopy.modflow.ModflowChd.load("inps/yo.chd", self.mf)
lpf = flopy.modflow.ModflowLpf(self.mf, hk=14.44, vka=14.44, ipakcb=53, sy=0.22)
self.mf.write_input()
def run(self):
success, buff = self.mf.run_model(silent=True)
headobj = bf.HeadFile(self.modelname + '.hds')
newheaddata = headobj.get_alldata()[-1][0]
return newheaddata
mdflw = Modflow()
mdflw.run()
Now, even if I change the EVT, RCH or WEL info, the results are same.
I even tried to not include the above files, still the results were same.
Any pointers?
This revision of your script results in different head results (since different groundwater recharge values are used). I used the bcf2ss MODFLOW-2005 input files as base files in the revised example.
Not entirely sure why your script wasn't working since your input files weren't available.
import os
import numpy as np
import flopy
class BASreader:
def __init__(self):
self.ibound = None
self.head = None
with open("inps/bas/ibound", "r") as f:
data = f.read().replace("-", " -").split()
data = [int(x) for x in data]
data = np.array(data).reshape(2, 10, 15)
self.ibound = data
with open("inps/bas/head", "r") as f:
data = f.read().split()
data = [float(x) for x in data]
self.head = np.array(data).reshape(2, 10, 15)
class Modflow:
def __init__(self, ws='outs', rech_val=.0040, wel_data=None):
self.model_ws = ws
self.modelname = 'gen1'
self.mf = flopy.modflow.Modflow(self.modelname, exe_name='mf2005',
model_ws=self.model_ws)
dis = flopy.modflow.ModflowDis.load("inps/yo.dis", self.mf, check=False)
nper = dis.nper
nstp = dis.nstp.array
basreader = BASreader()
bas = flopy.modflow.ModflowBas(self.mf, ibound=basreader.ibound,
strt=basreader.head)
self.prev_headdata = basreader.head
bcf = flopy.modflow.ModflowBcf.load("inps/yo.bc6", self.mf)
if wel_data is None:
wel_data = [[1, 2, 3, -35000.],
[1, 7, 3, -35000.]]
wel_spd = {1: wel_data}
wel = flopy.modflow.ModflowWel(self.mf,
stress_period_data=wel_spd)
riv = flopy.modflow.ModflowRiv.load('inps/yo.riv', self.mf, check=False)
rech = {}
for x in range(nper):
rech[x] = rech_val
rch = flopy.modflow.ModflowRch(self.mf, rech=rech)
pcg = flopy.modflow.ModflowPcg.load('inps/yo.pcg', self.mf)
stress_period_data = {}
for kper in range(nper):
for kstp in range(nstp[kper]):
stress_period_data[(kper, kstp)] = ['save head',
'save drawdown',
'save budget',
'print head',
'print drawdown',
'print budget']
oc = flopy.modflow.ModflowOc(self.mf,
stress_period_data=stress_period_data,
compact=True)
self.mf.write_input()
def run(self):
success, buff = self.mf.run_model(silent=True)
fpth = os.path.join(self.model_ws, self.modelname + '.hds')
headobj = flopy.utils.HeadFile(fpth)
newheaddata = headobj.get_data(idx=1)
return newheaddata
if __name__ == "__main__":
m1 = Modflow()
h1 = m1.run()
m2 = Modflow(rech_val=.0041)
h2 = m2.run()
assert np.array_equal(h1, h2), 'h1 does not equal h2'

PyQT table update crash easyly

i first use PyQT4 .
i'm create a QTableWidget to show runing message...
when my program run, it ill crash Within ten minutes.
i try diable my TableUpdate function , and it's don't crash again.
there is my code please help me
class table_work(QThread):
TableDataSignal = pyqtSignal()
def __init__(self,main_self):
# QThread.__init__(self)
super(table_work, self).__init__(main_self)
self.main_self = main_self
self.table_update_list = list()
#pyqtSlot(dict)
def update_table_thread_o(self,work):
try:
row_pos = work['row_position']
data = work['data']
table_key_sort = work['key_sort']
this_table = work['table']
k = 0
for table_key in table_key_sort:
this_table.setItem(row_pos, k, QTableWidgetItem(unicode(data[table_key])))
k += 1
del work
except:
pass
def update_table_thread(self):
main_self = self.main_self
table_work_list = self.table_update_list
while 1:
for work in self.table_update_list:
row_pos = work['row_position']
data = work['data']
table_key_sort = work['key_sort']
this_table = work['table']
k = 0
for table_key in table_key_sort:
this_table.setItem(row_pos, k, QTableWidgetItem(unicode(data[table_key])))
k += 1
time.sleep(0.5)
def run(self):
self.update_table_thread()
this's update table message
def update_table(self,address,change_obj=None,tabe_name='auto_card'):
sample_dict = dict()
table_key_sort = list()
now_table_sort = 0
if tabe_name == "auto_bot":
this_table = self.auto_bot_procc_table
table_data_list = self.auto_bot_procc_table_list
now_table_sort = self.auto_bot_now_table_sort
sample_dict['address'] = address
sample_dict['money'] = 0
sample_dict['run_time'] = 0
sample_dict['item_cd'] = u"60分鐘後"
sample_dict['stat'] = "Ready..."
sample_dict['sort'] = now_table_sort
table_key_sort.append('address')
table_key_sort.append('money')
table_key_sort.append('run_time')
table_key_sort.append('item_cd')
table_key_sort.append('stat')
if tabe_name == "auto_card":
this_table = self.process_table
table_data_list = self.now_procc_table_list
now_table_sort = self.now_table_sort
sample_dict['address'] = address
sample_dict['done_num'] = 0
sample_dict['pre_item'] = ""
sample_dict['procc'] = "Ready"
sample_dict['mission_procc'] = u"待命.."
sample_dict['mission_num'] = 0
sample_dict['mission_line'] = 0
sample_dict['update_time'] = db.get_time()
sample_dict['sort'] = now_table_sort
sample_dict['option'] = ""
table_key_sort.append('address')
table_key_sort.append('done_num')
table_key_sort.append('pre_item')
table_key_sort.append('mission_procc')
table_key_sort.append('procc')
table_key_sort.append('mission_num')
table_key_sort.append('mission_line')
table_key_sort.append('update_time')
if address not in table_data_list:
this_table.insertRow(sample_dict['sort'])
table_data_list[address] = sample_dict
sample_dict['sort'] = self.auto_bot_now_table_sort
self.auto_bot_now_table_sort += 1
acc_data = table_data_list[address]
if change_obj != None:
key = change_obj['key']
val = change_obj['val']
if key in acc_data:
acc_data[key] = val
acc_data['update_time'] = db.get_time()
rowPosition = acc_data['sort']
temp = dict()
temp['row_position'] = rowPosition
temp['data'] = acc_data
temp['key_sort'] = table_key_sort
temp['table'] = this_table
self.TableDataSignal.emit(temp)
del temp
Some time i get a ANS.
i'm a PYQT newbie , After this period of various projects experience.
I understand if you don't use Main Thread to Change UI, Always use sign/emit
even your code is worked,but always use sign/emit, Otherwise there will be a series of disasters.
you just like
class sample(QtCore.QThread):
table_data_change = QtCore.pyqtSignal(dict)
def __init__(self,main_win):
self.main = main_win
self.table_data_change.connect(self.main.change_fn)
def test(self):
data = dict()
data['btn'] = .....
data['val'] = .....
self.table_data_change.emit(data)
Save your time !

Python - WindowName for Compare with List

I am currently blocked on a point of a program in Python.
I wish to compare in a list, the WindowName event to launch directives.
Example:
import win32api
import pyHook
liste = ["Google", "Task"]
if event.WindowName == liste:
Screenshot ()
return True
else:
return False
Complete code, he work:
def OnMouseEvent(event):
global interval
data = '\n[' + str(time.ctime().split(' ')[3]) + ']' \
+ ' WindowName : ' + str(event.WindowName)
data += '\n\tButton:' + str(event.MessageName)
data += '\n\tClicked in (Position):' + str(event.Position)
data += '\n===================='
global t, start_time, pics_names
"""
Code Edit
"""
t = t + data
if len(t) > 300:
ScreenShot()
"""
Finish
"""
if len(t) > 500:
f = open('Logfile.txt', 'a')
f.write(t)
f.close()
t = ''
if int(time.time() - start_time) == int(interval):
Mail_it(t, pics_names)
start_time = time.time()
t = ''
return True
else:
return False
When i edit the code in """ doesn't work :
t = t + data
liste = ["Google", "Task"]
if event.WindowName == liste:
ScreenShot()
He return :
File "C:\Python26\lib\site-packages\pyHook\HookManager.py", line 324, in MouseSwitch func = self.mouse_funcs.get(msg) TypeError: an integer is required
I test this :
HookManager: func = self.keyboard_funcs.get(msg) to: func=self.keyboard_funcs.get( int(str(msg)) )
But is don't work, i think i note all problem.
Thanks for you help in advance :)

chatroom quiz bot: How to repeat quiz during idle time?

I am working on a quit bot in Python. Now I want to know how I can repeat the question after a certain idle time.
These are my global variables:
QUIZ_FILE = 'static/questions.txt'
QUIZ_TOTAL_LINES = 29
QUIZ_TIME_LIMIT = 40
QUIZ_IDLE_LIMIT = 3000000
QUIZ_RECURSIVE_MAX = 3000000
QUIZ_CURRENT_ANSWER = {}
QUIZ_CURRENT_HINT = {}
QUIZ_CURRENT_HINT_NEW = {}
QUIZ_CURRENT_TIME = {}
QUIZ_IDLENESS = {}
QUIZ_IDLE_ANSWER = {}
QUIZ_START = {}
QUIZ_IDLE_ANSWER_FIRSR = {}
QUIZ_NOWORD = '*'
MODE = 'M1'
PTS = 'P2'
ACC = 'A2'
Bot Time settings
import threading
HELP = u'help of command > "!quiz"'
def sectomin(time):
m = 0
s = 0
if time >= 60:
m = time / 60
if (m * 60) != 0:
s = time - (m * 60)
else:
s = 0
else:
m = 0
s = time
return str(m)+u'min. in '+str(s)+u'sec.'
def quiz_timer(groupchat, start_time):
global QUIZ_TIME_LIMIT
global QUIZ_CURRENT_TIME
time.sleep(QUIZ_TIME_LIMIT)
if QUIZ_CURRENT_TIME.has_key(groupchat) and QUIZ_CURRENT_ANSWER.has_key(groupchat) and start_time == QUIZ_CURRENT_TIME[groupchat]:
QUIZ_CURRENT_ANSWER[groupchat]
msg(groupchat, u'(!) time out! ' + sectomin(QUIZ_TIME_LIMIT) + u' passed.\nCorrect answer: ' + QUIZ_CURRENT_ANSWER[groupchat])
if QUIZ_IDLENESS.has_key(groupchat):
QUIZ_IDLENESS[groupchat] += 1
else:
QUIZ_IDLENESS[groupchat] = 1
if QUIZ_IDLENESS[groupchat] >= QUIZ_IDLE_LIMIT:
msg(groupchat, u'(!) quiz will be automatically completed for inaction! ' + str(QUIZ_IDLE_LIMIT) + ' unanswered questions.')
del QUIZ_CURRENT_ANSWER[groupchat]
quiz_list_scores(groupchat)
else:
quiz_ask_question(groupchat)
Method of asking question
def quiz_ask_question(groupchat):
global answer
global QUIZ_CURRENT_TIME
global question
global QUIZ_IDLE_ANSWER
global QUIZ_IDLE_ANSWER_FIRSR
QUIZ_IDLE_ANSWER = {groupchat:{}}
(question, answer) = quiz_new_question()
QUIZ_CURRENT_ANSWER[groupchat] = answer
QUIZ_CURRENT_HINT[groupchat] = None
QUIZ_CURRENT_HINT_NEW[groupchat] = None
QUIZ_CURRENT_TIME[groupchat] = time.time()
threading.Thread(None, quiz_timer, 'gch'+str(random.randrange(0,9999)), (groupchat, QUIZ_CURRENT_TIME[groupchat])).start()
msg(groupchat, u'(?) question: \n' + question)
I want to automatically recall the question every few seconds during sleep/idle time.
I cannot make it to work so that the bot can ask questions between QUIZ_TIME_LIMIT = 40 automatically.
Code to recall question on request
def handler_quiz_resend(type, source, body):
global question
groupchat = source[1]
if QUIZ_CURRENT_ANSWER.has_key(groupchat):
res = u'(*) current question: \n'+question
reply(type, source, res)
else:
reply(type, source, u'no quiz, '+HELP)

Categories

Resources