index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
30,916,914
vinosa75/script
refs/heads/main
/myapp/tasks.py
from time import sleep from celery import shared_task from .models import * from nsetools import * from datetime import datetime as dt from truedata_ws.websocket.TD import TD import websocket from celery.schedules import crontab from celery import Celery from celery.schedules import crontab import time from nsetools import Nse from myproject.celery import app from django_celery_beat.models import PeriodicTask, PeriodicTasks from datetime import timedelta from celery.exceptions import SoftTimeLimitExceeded from pytz import timezone import pendulum import calendar from datetime import date import time as te @shared_task def create_currency(): from datetime import datetime, time,timedelta pastDate = datetime.combine(datetime.now(timezone('Asia/Kolkata')), time(9,15)).time() nsepadDate = datetime.combine(datetime.now(timezone('Asia/Kolkata')), time(9,15)).date() # LiveEquityResult.objects.all().delete() LiveSegment.objects.filter(time__lte = pastDate).delete() LiveSegment.objects.filter(date__lt = nsepadDate).delete() pastDate = datetime.combine(datetime.now(timezone('Asia/Kolkata')), time(9,15)) segpastDate = datetime.combine(datetime.now(timezone('Asia/Kolkata')), time(9,15)).time() # LiveEquityResult.objects.all().delete() TestEquityResult.objects.filter(date__lte = pastDate).delete() LiveEquityResult.objects.filter(date__lte = pastDate).delete() LiveSegment.objects.filter(time__lte = segpastDate).delete() LiveSegment.objects.filter(date__lt = nsepadDate).delete() def initialEquity(): try: import requests url = 'https://www.truedata.in/downloads/symbol_lists/13.NSE_ALL_OPTIONS.txt' s = requests.get(url).content stringlist=[x.decode('utf-8').split('2')[0] for x in s.splitlines()] symbols = list(set(stringlist)) TrueDatausernamereal = 'tdws135' TrueDatapasswordreal = 'saaral@135' remove_list = ['BANKNIFTY', 'FINNIFTY', 'NIFTY', 'ASIANPAINT', 'BAJAJFINSV', 'BHARTIARTL', 'BHEL', 'BPCL', 'DEEPAKNTR', 'FEDERALBNK', 'HDFC', 'IOC', 'IRCTC', 'IPCALAB', 'NATIONALUM', 'NTPC', 'PNB', 'SHREECEM', 'VEDL', 'ASTRAL', 'BOSCHLTD', 'EICHERMOT', 'GMRINFRA', 'HDFCLIFE', 'IBULHSGFIN', 'ITC', 'L&TFH', 'BANKBARODA', 'IDFCFIRSTB', 'SAIL', 'IDEA'] fnolist = [i for i in symbols if i not in remove_list] # Default production port is 8082 in the library. Other ports may be given t oyou during trial. realtime_port = 8082 print('Starting Real Time Feed.... ') print(f'Port > {realtime_port}') td_app = TD(TrueDatausernamereal, TrueDatapasswordreal, live_port=realtime_port, historical_api=False) # print(symbols) req_ids = td_app.start_live_data(symbols) live_data_objs = {} te.sleep(3) liveData = {} for req_id in req_ids: # print(td_app.live_data[req_id].day_open) if (td_app.live_data[req_id].ltp) == None: continue else: liveData[td_app.live_data[req_id].symbol] = [td_app.live_data[req_id].ltp,td_app.live_data[req_id].day_open,td_app.live_data[req_id].day_high,td_app.live_data[req_id].day_low,td_app.live_data[req_id].prev_day_close,dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S'),td_app.live_data[req_id].change_perc] callcrossedset = LiveEquityResult.objects.filter(strike__contains="Call Crossed") callonepercentset = LiveEquityResult.objects.filter(strike="Call 1 percent") putcrossedset = LiveEquityResult.objects.filter(strike="Put Crossed") putonepercentset = LiveEquityResult.objects.filter(strike="Put 1 percent") opencallcross = LiveEquityResult.objects.filter(opencrossed="call") openputcross = LiveEquityResult.objects.filter(opencrossed="put") callcrossedsetDict = {} callonepercentsetDict = {} putcrossedsetDict = {} putonepercentsetDict = {} opencallcrossDict = {} openputcrossDict = {} for i in callcrossedset: callcrossedsetDict[i.symbol] = i.time for i in callonepercentset: callonepercentsetDict[i.symbol] = i.time for i in putcrossedset: putcrossedsetDict[i.symbol] = i.time for i in putonepercentset: putonepercentsetDict[i.symbol] = i.time for i in opencallcross: opencallcrossDict[i.symbol] = i.time for i in openputcross: openputcrossDict[i.symbol] = i.time # Graceful exit td_app.stop_live_data(symbols) td_app.disconnect() td_app.disconnect() for key,value in liveData.items(): if key in fnolist: if float(value[6]) >= 3: # print(key) if LiveSegment.objects.filter(symbol=key,segment="gain").exists(): LiveSegment.objects.filter(symbol=key,segment="gain").delete() gain = LiveSegment(symbol=key,segment="gain",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S'),doneToday="Yes") gain.save() else: gain = LiveSegment(symbol=key,segment="gain",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S'),doneToday="Yes") gain.save() elif float(value[6]) <= -3: if LiveSegment.objects.filter(symbol=key,segment="loss").exists(): LiveSegment.objects.filter(symbol=key,segment="loss").delete() loss = LiveSegment(symbol=key,segment="loss",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S'),doneToday="Yes") loss.save() else: loss = LiveSegment(symbol=key,segment="loss",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S'),doneToday="Yes") loss.save() elif float(value[6]) <= -0.30: if LiveSegment.objects.filter(symbol=key,segment="below").exists(): LiveSegment.objects.filter(symbol=key,segment="below").delete() loss = LiveSegment(symbol=key,segment="below",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S'),doneToday="Yes") loss.save() else: loss = LiveSegment(symbol=key,segment="below",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S'),doneToday="Yes") loss.save() elif float(value[6]) >= 0.30: if LiveSegment.objects.filter(symbol=key,segment="above").exists(): LiveSegment.objects.filter(symbol=key,segment="above").delete() loss = LiveSegment(symbol=key,segment="above",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S'),doneToday="Yes") loss.save() else: loss = LiveSegment(symbol=key,segment="above",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S'),doneToday="Yes") loss.save() gainList = list(LiveSegment.objects.filter(segment="gain").values_list('symbol', flat=True)) lossList = list(LiveSegment.objects.filter(segment="loss").values_list('symbol', flat=True)) except websocket.WebSocketConnectionClosedException as e: print('This caught the websocket exception ') td_app.disconnect() # return render(request,"testhtml.html",{'symbol':item,'counter':1}) except IndexError as e: print('This caught the exception') print(e) td_app.disconnect() # return render(request,"testhtml.html",{'symbol':item,'counter':1}) except Exception as e: print(e) td_app.disconnect() # return render(request,"testhtml.html",{'symbol':item,'counter':1}) equitypastdate = datetime.combine(datetime.now(timezone('Asia/Kolkata')), time(9,15)).strftime('%Y-%m-%d %H:%M:%S') timenow = datetime.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S') doneToday = LiveSegment.objects.values_list('doneToday', flat=True).distinct() if len(doneToday) > 0: doneToday = doneToday[0] else: doneToday = "" if timenow > equitypastdate and doneToday != "Yes": initialEquity() fnolist = [] gainList = list(LiveSegment.objects.filter(segment="gain").values_list('symbol', flat=True)) lossList = list(LiveSegment.objects.filter(segment="loss").values_list('symbol', flat=True)) segments = list(LiveSegment.objects.values_list('symbol', flat=True).distinct()) fnolist.extend(gainList) fnolist.extend(lossList) fnolist.extend(segments) fnolist = list(set(fnolist)) def OIPercentChange(df): print("Enter OIper") ce = df.loc[df['type'] == "CE"] pe = df.loc[df['type'] == "PE"] # ce_oipercent_df = ce.sort_values(by=['oi_change_perc'], ascending=False) ce_oipercent_df = ce.where(ce['oi_change_perc'] !=0 ).sort_values(by=['oi_change_perc'], ascending=False) # print(ce_oipercent_df) minvalue = ce.loc[ce['strike'] != 0].sort_values('strike', ascending=True) ceindex = minvalue.iloc[0].name peindex = ceindex.replace("CE", "PE") pe = pe[peindex:] ceoi1 = ce_oipercent_df.iloc[0]['oi_change_perc'] cestrike = ce_oipercent_df.iloc[0]['strike'] peoi1 = pe.loc[pe['strike']==ce_oipercent_df.iloc[0]['strike']].iloc[0]['oi_change_perc'] # print(ceoi1) # print(cestrike) # print(peoi1) pe_oipercent_df = pe.where(pe['oi_change_perc'] !=0 ).sort_values(by=['oi_change_perc'], ascending=False) ceoi2 = pe_oipercent_df.iloc[0]['oi_change_perc'] pestrike = pe_oipercent_df.iloc[0]['strike'] peoi2 = ce.loc[ce['strike']==pe_oipercent_df.iloc[0]['strike']].iloc[0]['oi_change_perc'] # print(ceoi2) # print(pestrike) # print(peoi2) import datetime as det # celtt = pe_oipercent_df.iloc[count]['ltt'] celtt = dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S') celtt = dt.strptime(str(celtt), "%Y-%m-%d %H:%M:%S").time() my_time_string = "15:30:00" my_datetime = det.datetime.strptime(my_time_string, "%H:%M:%S").time() if celtt > my_datetime: celtt = det.datetime.now().replace(hour=15,minute=30,second=00).strftime("%Y-%m-%d %H:%M:%S") peltt = det.datetime.now().replace(hour=15,minute=30,second=00).strftime("%Y-%m-%d %H:%M:%S") else: celtt = pe_oipercent_df.iloc[0]['ltt'] peltt = pe_oipercent_df.iloc[0]['ltt'] OIPercentChange = {"celtt":celtt,"ceoi1":ceoi1,"cestrike":cestrike,"peoi1":peoi1,"peltt":peltt,"peoi2":peoi2,"pestrike":pestrike,"ceoi2":ceoi2} print("Exit OIper") return OIPercentChange def OITotal(df,item,dte): print("Enter OITotl") ce = df.loc[df['type'] == "CE"] pe = df.loc[df['type'] == "PE"] # print("before final df") final_df = ce.loc[ce['oi'] != 0].sort_values('oi', ascending=False) minvalue = ce.loc[ce['strike'] != 0].sort_values('strike', ascending=True) ceindex = minvalue.iloc[0].name peindex = ceindex.replace("CE", "PE") pe = pe[peindex:] peoi1 = pe.loc[pe['strike']==final_df.iloc[0]['strike']].iloc[0]['oi'] count = 0 while peoi1 == 0: count = count + 1 peoi1 = pe.loc[pe['strike']==final_df.iloc[count]['strike']].iloc[0]['oi'] cestrike = final_df.iloc[count]['strike'] ceoi1 = final_df.iloc[count]['oi'] import datetime as det celtt = final_df.iloc[count]['ltt'] celtt = dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S') celtt = dt.strptime(str(celtt), "%Y-%m-%d %H:%M:%S").time() my_time_string = "15:30:00" my_datetime = det.datetime.strptime(my_time_string, "%H:%M:%S").time() if celtt > my_datetime: celtt = det.datetime.now().replace(hour=15,minute=30,second=00).strftime("%Y-%m-%d %H:%M:%S") peltt = det.datetime.now().replace(hour=15,minute=30,second=00).strftime("%Y-%m-%d %H:%M:%S") else: celtt = final_df.iloc[0]['ltt'] peltt = final_df.iloc[0]['ltt'] # print(ceoi1) # print(cestrike) # print(peoi1) final_df = pe.loc[pe['oi'] != 0].sort_values('oi', ascending=False) ceoi2 = ce.loc[ce['strike']==final_df.iloc[0]['strike']].iloc[0]['oi'] count = 0 while ceoi2 == 0: count = count + 1 ceoi2 = ce.loc[ce['strike']==final_df.iloc[count]['strike']].iloc[0]['oi'] pestrike = final_df.iloc[count]['strike'] peoi2 = final_df.iloc[count]['oi'] # print(ceoi2) # print(pestrike) # print(peoi2) OITot = {"celtt":celtt,"ceoi1":ceoi1,"cestrike":cestrike,"peoi1":peoi1,"peltt":peltt,"peoi2":peoi2,"pestrike":pestrike,"ceoi2":ceoi2} print("Exit OITotl") return OITot def OIChange(df,item,dte): ce = df.loc[df['type'] == "CE"] pe = df.loc[df['type'] == "PE"] # print("1") final_df = ce.loc[ce['oi_change'] != 0].sort_values('oi_change', ascending=False) minvalue = ce.loc[ce['strike'] != 0].sort_values('strike', ascending=True) # print("2") ceindex = minvalue.iloc[0].strike # peindex = ceindex.replace("CE", "PE") inde = pe[pe['strike']==ceindex].index.values pe = pe[inde[0]:] print(pe) # ce.to_excel("ce.xlsx") # print("3") print(final_df.iloc[0]['strike']) print(pe.loc[pe['strike']==str(final_df.iloc[0]['strike'])]) peoi1 = pe.loc[pe['strike']==str(final_df.iloc[0]['strike'])].iloc[0]['oi_change'] count = 0 # print("4") while peoi1 == 0: count = count + 1 peoi1 = pe.loc[pe['strike']==final_df.iloc[count]['strike']].iloc[0]['oi_change'] # print("5") cestrike = final_df.iloc[count]['strike'] ceoi1 = final_df.iloc[count]['oi_change'] import datetime as det # print("6") celtt = final_df.iloc[count]['ltt'] celtt = dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S') celtt = dt.strptime(str(celtt), "%Y-%m-%d %H:%M:%S").time() my_time_string = "15:30:00" my_datetime = det.datetime.strptime(my_time_string, "%H:%M:%S").time() if celtt > my_datetime: celtt = det.datetime.now().replace(hour=15,minute=30,second=00).strftime("%Y-%m-%d %H:%M:%S") peltt = det.datetime.now().replace(hour=15,minute=30,second=00).strftime("%Y-%m-%d %H:%M:%S") else: celtt = final_df.iloc[0]['ltt'] peltt = final_df.iloc[0]['ltt'] print(ceoi1) print(cestrike) print(peoi1) # print("7") final_df = pe.loc[pe['oi_change'] != 0].sort_values('oi_change', ascending=False) ceoi2 = ce.loc[ce['strike']==final_df.iloc[0]['strike']].iloc[0]['oi_change'] count = 0 # print("8") while ceoi2 == 0: count = count + 1 ceoi2 = ce.loc[ce['strike']==final_df.iloc[count]['strike']].iloc[0]['oi_change'] pestrike = final_df.iloc[count]['strike'] peoi2 = final_df.iloc[count]['oi_change'] peltt = final_df.iloc[count]['ltt'] # print(ceoi2) # print(pestrike) # print(peoi2) OIChan = {"celtt":celtt,"ceoi1":ceoi1,"cestrike":cestrike,"peoi1":peoi1,"peltt":peltt,"peoi2":peoi2,"pestrike":pestrike,"ceoi2":ceoi2} print("Exit OiChnge") return OIChan def optionChainprocess(df,item,dte): # Total OI Calculation from Option chain FutureData = {} # value1 = LiveOIChange.objects.all() # value2 = LiveOITotal.objects.all() # print("Before changev") OIChangeValue = OIChange(df,item,dte) print("after change") if OIChangeValue == False: print("returning false") # return render(request,"testhtml.html",{'symbol':item,'counter':1}) OITotalValue = OITotal(df,item,dte) if OITotalValue == False: print("returning false") # return render(request,"testhtml.html",{'symbol':item,'counter':1}) percentChange = OIPercentChange(df) # strikeGap =float(df['strike'].unique()[1]) - float(df['strike'].unique()[0]) midvalue = round(len(df['strike'].unique())/2) strikeGap =float(df['strike'].unique()[midvalue]) - float(df['strike'].unique()[midvalue-1]) FutureData[item] = [OITotalValue['cestrike'],OITotalValue['pestrike'],strikeGap] # print(FutureData) # Percentage calculation from equity data newDict = {} # for key,value in FutureData.items(): # Call 1 percent callone = float(OITotalValue['cestrike']) - (float(strikeGap))*0.1 # Call 1/2 percent callhalf = float(OITotalValue['cestrike']) - (float(strikeGap))*0.05 # Put 1 percent putone = float(OITotalValue['pestrike']) + (float(strikeGap))*0.1 # Put 1/2 percent puthalf = float(OITotalValue['pestrike']) + (float(strikeGap))*0.05 newDict[item] = [float(OITotalValue['cestrike']),float(OITotalValue['pestrike']),callone,putone,callhalf,puthalf] # # Fetching today's date dat = dt.today() # print("before deletiong") from datetime import datetime, time pastDate = datetime.combine(datetime.now(timezone('Asia/Kolkata')), time(9,15)) # LiveEquityResult.objects.all().delete() LiveOITotalAllSymbol.objects.filter(time__lte = pastDate).delete() # # Deleting past historical data in the database HistoryOIChange.objects.filter(time__lte = pastDate).delete() HistoryOITotal.objects.filter(time__lte = pastDate).delete() HistoryOIPercentChange.objects.filter(time__lte = pastDate).delete() # Deleting live data LiveOITotal.objects.filter(time__lte = pastDate).delete() LiveOIChange.objects.filter(time__lte = pastDate).delete() LiveOIPercentChange.objects.filter(time__lte = pastDate).delete() # print("After deletion") value1 = LiveOIChange.objects.filter(symbol=item) if len(value1) > 0: if (value1[0].callstrike != OIChangeValue['cestrike']) or (value1[0].putstrike != OIChangeValue['pestrike']): # Adding to history table ChangeOIHistory = HistoryOIChange(time=value1[0].time,call1=value1[0].call1,call2=value1[0].call2,put1=value1[0].put1,put2=value1[0].put2,callstrike=value1[0].callstrike,putstrike=value1[0].putstrike,symbol=value1[0].symbol,expiry=value1[0].expiry) ChangeOIHistory.save() # deleting live table data LiveOIChange.objects.filter(symbol=item).delete() # Creating in live data ChangeOICreation = LiveOIChange(time=OIChangeValue['celtt'],call1=OIChangeValue['ceoi1'],call2=OIChangeValue['ceoi2'],put1=OIChangeValue['peoi1'],put2=OIChangeValue['peoi2'],callstrike=OIChangeValue['cestrike'],putstrike=OIChangeValue['pestrike'],symbol=item,expiry=dte) ChangeOICreation.save() else: # deleting live table data LiveOIChange.objects.filter(symbol=item).delete() # Creating in live data ChangeOICreation = LiveOIChange(time=OIChangeValue['celtt'],call1=OIChangeValue['ceoi1'],call2=OIChangeValue['ceoi2'],put1=OIChangeValue['peoi1'],put2=OIChangeValue['peoi2'],callstrike=OIChangeValue['cestrike'],putstrike=OIChangeValue['pestrike'],symbol=item,expiry=dte) ChangeOICreation.save() else: ChangeOICreation = LiveOIChange(time=OIChangeValue['celtt'],call1=OIChangeValue['ceoi1'],call2=OIChangeValue['ceoi2'],put1=OIChangeValue['peoi1'],put2=OIChangeValue['peoi2'],callstrike=OIChangeValue['cestrike'],putstrike=OIChangeValue['pestrike'],symbol=item,expiry=dte) ChangeOICreation.save() # print("value1 crossed") value2 = LiveOITotal.objects.filter(symbol=item) if len(value2) > 0: if (value2[0].callstrike != OITotalValue['cestrike']) or (value2[0].putstrike != OITotalValue['pestrike']): # Adding to history table TotalOIHistory = HistoryOITotal(time=value2[0].time,call1=value2[0].call1,call2=value2[0].call2,put1=value2[0].put1,put2=value2[0].put2,callstrike=value2[0].callstrike,putstrike=value2[0].putstrike,symbol=value2[0].symbol,expiry=value2[0].expiry) TotalOIHistory.save() # deleting live table data LiveOITotal.objects.filter(symbol=item).delete() # Creating in live data TotalOICreation = LiveOITotal(time=OITotalValue['celtt'],call1=OITotalValue['ceoi1'],call2=OITotalValue['ceoi2'],put1=OITotalValue['peoi1'],put2=OITotalValue['peoi2'],callstrike=OITotalValue['cestrike'],putstrike=OITotalValue['pestrike'],symbol=item,expiry=dte,strikegap=strikeGap) TotalOICreation.save() # Live data for equity LiveOITotalAllSymbol.objects.filter(symbol=item).delete() TotalOICreationAll = LiveOITotalAllSymbol(time=OITotalValue['celtt'],call1=OITotalValue['ceoi1'],call2=OITotalValue['ceoi2'],put1=OITotalValue['peoi1'],put2=OITotalValue['peoi2'],callstrike=OITotalValue['cestrike'],putstrike=OITotalValue['pestrike'],symbol=item,expiry=dte,callone=callone,putone=putone,callhalf=callhalf,puthalf=puthalf) TotalOICreationAll.save() else: # deleting live table data LiveOITotal.objects.filter(symbol=item).delete() # Creating in live data TotalOICreation = LiveOITotal(time=OITotalValue['celtt'],call1=OITotalValue['ceoi1'],call2=OITotalValue['ceoi2'],put1=OITotalValue['peoi1'],put2=OITotalValue['peoi2'],callstrike=OITotalValue['cestrike'],putstrike=OITotalValue['pestrike'],symbol=item,expiry=dte,strikegap=strikeGap) TotalOICreation.save() # Live data for equity LiveOITotalAllSymbol.objects.filter(symbol=item).delete() TotalOICreationAll = LiveOITotalAllSymbol(time=OITotalValue['celtt'],call1=OITotalValue['ceoi1'],call2=OITotalValue['ceoi2'],put1=OITotalValue['peoi1'],put2=OITotalValue['peoi2'],callstrike=OITotalValue['cestrike'],putstrike=OITotalValue['pestrike'],symbol=item,expiry=dte,callone=callone,putone=putone,callhalf=callhalf,puthalf=puthalf) TotalOICreationAll.save() else: TotalOICreation = LiveOITotal(time=OITotalValue['celtt'],call1=OITotalValue['ceoi1'],call2=OITotalValue['ceoi2'],put1=OITotalValue['peoi1'],put2=OITotalValue['peoi2'],callstrike=OITotalValue['cestrike'],putstrike=OITotalValue['pestrike'],symbol=item,expiry=dte,strikegap=strikeGap) TotalOICreation.save() # Live data for equity LiveOITotalAllSymbol.objects.filter(symbol=item).delete() TotalOICreationAll = LiveOITotalAllSymbol(time=OITotalValue['celtt'],call1=OITotalValue['ceoi1'],call2=OITotalValue['ceoi2'],put1=OITotalValue['peoi1'],put2=OITotalValue['peoi2'],callstrike=OITotalValue['cestrike'],putstrike=OITotalValue['pestrike'],symbol=item,expiry=dte,callone=callone,putone=putone,callhalf=callhalf,puthalf=puthalf) TotalOICreationAll.save() value3 = LiveOIPercentChange.objects.filter(symbol=item) if len(value3) > 0: if (value3[0].callstrike != percentChange['cestrike']) or (value3[0].putstrike != percentChange['pestrike']): # Adding to history table ChangeOIPercentHistory = HistoryOIPercentChange(time=value3[0].time,call1=value3[0].call1,call2=value3[0].call2,put1=value3[0].put1,put2=value3[0].put2,callstrike=value3[0].callstrike,putstrike=value3[0].putstrike,symbol=value3[0].symbol,expiry=value3[0].expiry) ChangeOIPercentHistory.save() # deleting live table data LiveOIPercentChange.objects.filter(symbol=item).delete() # Creating in live data ChangeOIPercentCreation = LiveOIPercentChange(time=percentChange['celtt'],call1=percentChange['ceoi1'],call2=percentChange['ceoi2'],put1=percentChange['peoi1'],put2=percentChange['peoi2'],callstrike=percentChange['cestrike'],putstrike=percentChange['pestrike'],symbol=item,expiry=dte) ChangeOIPercentCreation.save() else: # deleting live table data LiveOIPercentChange.objects.filter(symbol=item).delete() # Creating in live data ChangeOIPercentCreation = LiveOIPercentChange(time=percentChange['celtt'],call1=percentChange['ceoi1'],call2=percentChange['ceoi2'],put1=percentChange['peoi1'],put2=percentChange['peoi2'],callstrike=percentChange['cestrike'],putstrike=percentChange['pestrike'],symbol=item,expiry=dte) ChangeOIPercentCreation.save() else: ChangeOIPercentCreation = LiveOIPercentChange(time=percentChange['celtt'],call1=percentChange['ceoi1'],call2=percentChange['ceoi2'],put1=percentChange['peoi1'],put2=percentChange['peoi2'],callstrike=percentChange['cestrike'],putstrike=percentChange['pestrike'],symbol=item,expiry=dte) ChangeOIPercentCreation.save() # Fetching the F&NO symbol list TrueDatausername = 'tdws127' TrueDatapassword = 'saaral@127' sampleDict = {} count=1 lenthree = (len(fnolist))%3 for r,g,b in zip(*[iter(fnolist)]*3): # realtime try: TrueDatausernamereal = 'tdws135' TrueDatapasswordreal = 'saaral@135' import requests url = 'https://www.truedata.in/downloads/symbol_lists/13.NSE_ALL_OPTIONS.txt' s = requests.get(url).content stringlist=[x.decode('utf-8').split('2')[0] for x in s.splitlines()] symbols = list(set(stringlist)) remove_list = ['BANKNIFTY', 'FINNIFTY', 'NIFTY', 'ASIANPAINT','BHARTIARTL', 'BHEL', 'BPCL', 'DEEPAKNTR', 'FEDERALBNK', 'HDFC', 'IOC', 'IRCTC', 'IPCALAB', 'MRF', 'NATIONALUM', 'NTPC', 'PNB','VEDL', 'ASTRAL', 'BOSCHLTD', 'EICHERMOT', 'GMRINFRA', 'HDFCLIFE', 'IBULHSGFIN', 'ITC', 'L&TFH', 'PAGEIND', 'BANKBARODA', 'IDFCFIRSTB','IDEA'] fnolistreal = [i for i in symbols if i not in remove_list] # Default production port is 8082 in the library. Other ports may be given t oyou during trial. realtime_port = 8082 print('Starting Real Time Feed.... ') print(f'Port > {realtime_port}') td_app = TD(TrueDatausernamereal, TrueDatapasswordreal, live_port=realtime_port, historical_api=False) # print(symbols) req_ids = td_app.start_live_data(symbols) live_data_objs = {} te.sleep(3) liveData = {} for req_id in req_ids: # print(td_app.live_data[req_id].day_open) if (td_app.live_data[req_id].ltp) == None: continue else: liveData[td_app.live_data[req_id].symbol] = [td_app.live_data[req_id].ltp,td_app.live_data[req_id].day_open,td_app.live_data[req_id].day_high,td_app.live_data[req_id].day_low,td_app.live_data[req_id].prev_day_close,dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S'),td_app.live_data[req_id].change_perc] # Finding out the pastdate from datetime import datetime, timedelta pastDate = datetime.combine(datetime.now(timezone('Asia/Kolkata')), time(9,15)) segpastDate = datetime.combine(datetime.now(timezone('Asia/Kolkata')), time(9,15)).time() nsepadDate = datetime.combine(datetime.now(timezone('Asia/Kolkata')), time(9,15)).date() # LiveEquityResult.objects.all().delete() LiveEquityResult.objects.filter(date__lte = pastDate).delete() removeList = ["NIFTY","BANKNIFTY","FINNIFTY"] callcrossedset = LiveEquityResult.objects.filter(strike__contains="Call Crossed") callonepercentset = LiveEquityResult.objects.filter(strike="Call 1 percent") putcrossedset = LiveEquityResult.objects.filter(strike="Put Crossed") putonepercentset = LiveEquityResult.objects.filter(strike="Put 1 percent") opencallcross = LiveEquityResult.objects.filter(opencrossed="call") openputcross = LiveEquityResult.objects.filter(opencrossed="put") callcrossedsetDict = {} callonepercentsetDict = {} putcrossedsetDict = {} putonepercentsetDict = {} opencallcrossDict = {} openputcrossDict = {} for i in callcrossedset: callcrossedsetDict[i.symbol] = i.time for i in callonepercentset: callonepercentsetDict[i.symbol] = i.time for i in putcrossedset: putcrossedsetDict[i.symbol] = i.time for i in putonepercentset: putonepercentsetDict[i.symbol] = i.time for i in opencallcross: opencallcrossDict[i.symbol] = i.time for i in openputcross: openputcrossDict[i.symbol] = i.time # Graceful exit td_app.stop_live_data(symbols) td_app.disconnect() td_app.disconnect() # print(liveData) # LiveSegment.objects.filter(time__lte = pastDate,date__lte = nsepadDate).delete() LiveSegment.objects.filter(time__lte = segpastDate).delete() LiveSegment.objects.filter(date__lt = nsepadDate).delete() for key,value in liveData.items(): if key in fnolistreal: if float(value[6]) >= 3: if len(LiveSegment.objects.filter(symbol=key,segment="gain")) > 0: LiveSegment.objects.filter(symbol=key,segment="gain").delete() gain = LiveSegment(symbol=key,segment="gain",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S')) gain.save() else: gain = LiveSegment(symbol=key,segment="gain",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S')) gain.save() elif float(value[6]) <= -3: if len(LiveSegment.objects.filter(symbol=key,segment="loss")) > 0: LiveSegment.objects.filter(symbol=key,segment="loss").delete() loss = LiveSegment(symbol=key,segment="loss",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S')) loss.save() else: loss = LiveSegment(symbol=key,segment="loss",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S')) loss.save() # elif float(value[6]) <= -0.30: # if len(LiveSegment.objects.filter(symbol=key,segment="below")) > 0: # LiveSegment.objects.filter(symbol=key,segment="below").delete() # loss = LiveSegment(symbol=key,segment="below",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S')) # loss.save() # else: # loss = LiveSegment(symbol=key,segment="below",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S')) # loss.save() # elif float(value[6]) >= 0.30: # if len(LiveSegment.objects.filter(symbol=key,segment="above")) > 0: # LiveSegment.objects.filter(symbol=key,segment="above").delete() # loss = LiveSegment(symbol=key,segment="above",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S')) # loss.save() # else: # loss = LiveSegment(symbol=key,segment="above",change_perc=value[6],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d'),time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S')) # loss.save() gainList = list(LiveSegment.objects.filter(segment="gain").values_list('symbol', flat=True)) lossList = list(LiveSegment.objects.filter(segment="loss").values_list('symbol', flat=True)) # History Check for e in LiveOITotalAllSymbol.objects.all(): # print(e.symbol) # callcross = TestEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="common",opencrossed="common",time=dt.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S'),date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) # callcross.save() # History Check historyLen = HistoryOITotal.objects.filter(symbol=e.symbol) if len(historyLen) > 0: historyStrike = HistoryOITotal.objects.filter(symbol=e.symbol).earliest('time') strikegp = LiveOITotal.objects.filter(symbol=e.symbol) callstrike = historyStrike.callstrike putstrike = historyStrike.putstrike # Call 1 percent callone = float(callstrike) - (float(strikegp[0].strikegap))*0.1 # Put 1 percent putone = float(putstrike) + (float(strikegp[0].strikegap))*0.1 else: callstrike = e.callstrike putstrike = e.putstrike callone = e.callone putone = e.putone if e.symbol in liveData and e.symbol not in removeList and e.symbol in gainList: # Call if liveData[e.symbol][1] > float(callstrike): if e.symbol in opencallcrossDict: LiveEquityResult.objects.filter(symbol = e.symbol).delete() callcross = LiveEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="Call Crossed",opencrossed="call",time=opencallcrossDict[e.symbol],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) callcross.save() continue else: callcross = LiveEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="Call Crossed",opencrossed="call",time=liveData[e.symbol][5],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) callcross.save() continue if liveData[e.symbol][0] > float(callstrike) or liveData[e.symbol][1] > float(callstrike): if e.symbol in callcrossedsetDict: # print("Yes") # Deleting the older LiveEquityResult.objects.filter(symbol = e.symbol).delete() # updating latest data # print("Yes") callcross = LiveEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="Call Crossed",opencrossed="Nil",time=callcrossedsetDict[e.symbol],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) callcross.save() continue else: # print("Call crossed") callcross = LiveEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="Call Crossed",opencrossed="Nil",time=liveData[e.symbol][5],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) callcross.save() elif liveData[e.symbol][0] >= float(callone) and liveData[e.symbol][0] <= float(callstrike): if e.symbol in callcrossedsetDict: # print("Already crossed") continue else: if e.symbol in callonepercentsetDict: # print("Already crossed 1 percent") LiveEquityResult.objects.filter(symbol = e.symbol).delete() # updating latest data callcross = LiveEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="Call 1 percent",opencrossed="Nil",time=callonepercentsetDict[e.symbol],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) callcross.save() continue else: # print("Call 1 percent") callone = LiveEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="Call 1 percent",opencrossed="Nil",time=liveData[e.symbol][5],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) callone.save() # Put if e.symbol in liveData and e.symbol not in removeList and e.symbol in lossList: if liveData[e.symbol][1] < float(putstrike): if e.symbol in openputcrossDict: LiveEquityResult.objects.filter(symbol = e.symbol).delete() putcross = LiveEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="Put Crossed",opencrossed="put",time=openputcrossDict[e.symbol],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) putcross.save() continue else: putcross = LiveEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="Put Crossed",opencrossed="put",time=liveData[e.symbol][5],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) putcross.save() continue if liveData[e.symbol][0] < float(putstrike) or liveData[e.symbol][2] < float(putstrike): if e.symbol in putcrossedsetDict: # Deleting the older LiveEquityResult.objects.filter(symbol =e.symbol).delete() # updating latest data putcross = LiveEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="Put Crossed",opencrossed="Nil",time=putcrossedsetDict[e.symbol],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) putcross.save() # print("put crossed updating only the data") continue else: # print("Put crossed") putcross = LiveEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="Put Crossed",opencrossed="Nil",time=liveData[e.symbol][5],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) putcross.save() elif liveData[e.symbol][0] <= float(putone) and liveData[e.symbol][0] >= float(putstrike): if e.symbol in putcrossedsetDict: # print("Already crossed put") continue else: if e.symbol in putonepercentsetDict: # print("Already crossed 1 percent") LiveEquityResult.objects.filter(symbol =e.symbol).delete() # updating latest data putcross = LiveEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="Put 1 percent",opencrossed="Nil",time=putonepercentsetDict[e.symbol],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) putcross.save() continue else: # print("Put 1 percent") putone = LiveEquityResult(symbol=e.symbol,open=liveData[e.symbol][1],high=liveData[e.symbol][2],low=liveData[e.symbol][3],prev_day_close=liveData[e.symbol][4],ltp=liveData[e.symbol][0],strike="Put 1 percent",opencrossed="Nil",time=liveData[e.symbol][5],date=dt.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S')) putone.save() except websocket.WebSocketConnectionClosedException as e: print('This caught the websocket exception in equity realtime') td_app.disconnect() td_app.disconnect() # return render(request,"testhtml.html",{'symbol':item,'counter':1}) except IndexError as e: print('This caught the exception in equity realtime') print(e) td_app.disconnect() td_app.disconnect() # return render(request,"testhtml.html",{'symbol':item,'counter':1}) except Exception as e: print(e) td_app.disconnect() td_app.disconnect() # return render(request,"testhtml.html",{'symbol':item,'counter':1}) # optionchain 3 symbols try: exceptionList = ['NIFTY','BANKNIFTY','FINNIFTY'] if r in exceptionList: if calendar.day_name[date.today().weekday()] == "Thrusday": expiry = date.today() expiry = "7-Oct-2021" dte = dt.strptime(expiry, '%d-%b-%Y') # print("inside thursday") else: expiry = pendulum.now().next(pendulum.THURSDAY).strftime('%d-%b-%Y') expiry = "7-Oct-2021" dte = dt.strptime(expiry, '%d-%b-%Y') else: # print("inside monthend") expiry = "28-Oct-2021" dte = dt.strptime(expiry, '%d-%b-%Y') # print("After exception") # td_obj = TD(TrueDatausername, TrueDatapassword, log_level= logging.WARNING ) symbol1 = r symbol2 = g symbol3 = b td_obj = TD('tdws127', 'saaral@127') first_chain = td_obj.start_option_chain( symbol1 , dt(dte.year , dte.month , dte.day) ,chain_length = 74) second_chain = td_obj.start_option_chain( symbol2 , dt(dte.year , dte.month , dte.day) ,chain_length = 74) third_chain = td_obj.start_option_chain( symbol3 , dt(dte.year , dte.month , dte.day) ,chain_length = 74) te.sleep(3) df1 = first_chain.get_option_chain() df2 = second_chain.get_option_chain() df3 = third_chain.get_option_chain() first_chain.stop_option_chain() second_chain.stop_option_chain() third_chain.stop_option_chain() td_obj.disconnect() td_obj.disconnect() # td_app.disconnect() sampleDict[symbol1] = df1 print(df1) print(df2) print(df3) # print(count) # print(item) count = count + 1 optionChainprocess(df1,symbol1,dte) optionChainprocess(df2,symbol2,dte) optionChainprocess(df3,symbol3,dte) except websocket.WebSocketConnectionClosedException as e: print('This caught the websocket exception in optionchain realtime') td_obj.disconnect() td_obj.disconnect() except IndexError as e: print('This caught the exception in option chain realtime') print(e) td_obj.disconnect() td_obj.disconnect() except Exception as e: print(e) td_obj.disconnect() td_obj.disconnect() if lenthree == 2: try: exceptionList = ['NIFTY','BANKNIFTY','FINNIFTY'] if fnolist[-1] in exceptionList: if calendar.day_name[date.today().weekday()] == "Thrusday": expiry = date.today() expiry = "7-Oct-2021" dte = dt.strptime(expiry, '%d-%b-%Y') # print("inside thursday") else: expiry = pendulum.now().next(pendulum.THURSDAY).strftime('%d-%b-%Y') expiry = "7-Oct-2021" dte = dt.strptime(expiry, '%d-%b-%Y') else: # print("inside monthend") expiry = "28-Oct-2021" dte = dt.strptime(expiry, '%d-%b-%Y') # print("After exception") # td_obj = TD(TrueDatausername, TrueDatapassword, log_level= logging.WARNING ) symbol1 = fnolist[-1] symbol2 = fnolist[-2] td_obj = TD('tdws127', 'saaral@127') first_chain = td_obj.start_option_chain( symbol1 , dt(dte.year , dte.month , dte.day) ,chain_length = 75) second_chain = td_obj.start_option_chain( symbol2 , dt(dte.year , dte.month , dte.day) ,chain_length = 75) te.sleep(3) df1 = first_chain.get_option_chain() df2 = second_chain.get_option_chain() first_chain.stop_option_chain() second_chain.stop_option_chain() td_obj.disconnect() td_obj.disconnect() sampleDict[symbol1] = df1 print(df1) print(df2) # print(count) # print(item) count = count + 1 optionChainprocess(df1,symbol1,dte) optionChainprocess(df2,symbol2,dte) except websocket.WebSocketConnectionClosedException as e: print('This caught the websocket exception in optionchain realtime ') td_obj.disconnect() td_obj.disconnect() except IndexError as e: print('This caught the exception in optionchain realtime') print(e) td_obj.disconnect() td_obj.disconnect() except Exception as e: print(e) td_obj.disconnect() td_obj.disconnect() sleep(1) elif lenthree == 1: try: exceptionList = ['NIFTY','BANKNIFTY','FINNIFTY'] if fnolist[-1] in exceptionList: if calendar.day_name[date.today().weekday()] == "Thrusday": expiry = date.today() expiry = "7-Oct-2021" dte = dt.strptime(expiry, '%d-%b-%Y') # print("inside thursday") else: expiry = pendulum.now().next(pendulum.THURSDAY).strftime('%d-%b-%Y') expiry = "7-Oct-2021" dte = dt.strptime(expiry, '%d-%b-%Y') else: # print("inside monthend") expiry = "28-Oct-2021" dte = dt.strptime(expiry, '%d-%b-%Y') # print("After exception") # td_obj = TD(TrueDatausername, TrueDatapassword, log_level= logging.WARNING ) symbol1 = fnolist[-1] td_obj = TD('tdws127', 'saaral@127') first_chain = td_obj.start_option_chain( symbol1 , dt(dte.year , dte.month , dte.day) ,chain_length = 75) te.sleep(3) df1 = first_chain.get_option_chain() first_chain.stop_option_chain() td_obj.disconnect() td_obj.disconnect() sampleDict[symbol1] = df1 print(df1) # print(count) # print(item) count = count + 1 optionChainprocess(df1,symbol1,dte) except websocket.WebSocketConnectionClosedException as e: print('This caught the websocket exception in optionchain realtime') td_obj.disconnect() td_obj.disconnect() except IndexError as e: print('This caught the exception in optionchain realtime') print(e) td_obj.disconnect() td_obj.disconnect() except Exception as e: print(e) td_obj.disconnect() td_obj.disconnect() sleep(1) while True: create_currency()
{"/myapp/views.py": ["/myapp/models.py"], "/myapp/tasks.py": ["/myapp/models.py", "/myproject/celery.py"]}
30,916,915
vinosa75/script
refs/heads/main
/myapp/Sample.py
Entry = 15135 StrikePrice = 14950 outputValue = (Entry-StrikePrice)/4 count = 0 sampleList = [] for i in range(0,10): print(outputValue) NewValue = outputValue*(i+1) OneFourth = round(outputValue*(count+0.25),2) Half = round(outputValue*(count+0.50),2) ThreeFourth = round(outputValue*(count+0.75),2) count = count+1 sampleList.append((i,NewValue,OneFourth,Half,ThreeFourth))
{"/myapp/views.py": ["/myapp/models.py"], "/myapp/tasks.py": ["/myapp/models.py", "/myproject/celery.py"]}
30,916,916
vinosa75/script
refs/heads/main
/myproject/celery.py
from __future__ import absolute_import, unicode_literals import os from celery import Celery # Default Django settings module for Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') app = Celery('myproject') # Using a string here eliminates the need to serialize # the configuration object to child processes by the Celery worker. # - namespace='CELERY' means all celery-related configuration keys app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django applications. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) # app.conf.beat_schedule = { # 'add-every-30-seconds': { # 'task': 'tasks.create_equity', # 'schedule': 20.0, # }, # } app.control.time_limit('print_msg_main', soft=25, hard=30, reply=True) # app.conf.beat_schedule = { # "see-you-in-ten-seconds-task": { # "task": 'print_msg_main', # "schedule": 40.0 # } # } app.conf.timezone = 'UTC'
{"/myapp/views.py": ["/myapp/models.py"], "/myapp/tasks.py": ["/myapp/models.py", "/myproject/celery.py"]}
30,916,917
vinosa75/script
refs/heads/main
/myapp/migrations/0005_liveoipercentchange.py
# Generated by Django 3.1.6 on 2021-09-23 00:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0004_liveequityresult_opencrossed'), ] operations = [ migrations.CreateModel( name='LiveOIPercentChange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.DateTimeField()), ('call1', models.CharField(default='', max_length=20)), ('call2', models.CharField(default='', max_length=20)), ('put1', models.CharField(default='', max_length=20)), ('put2', models.CharField(default='', max_length=20)), ('callstrike', models.CharField(max_length=20)), ('putstrike', models.CharField(max_length=20)), ('symbol', models.CharField(max_length=20)), ('expiry', models.DateField()), ('strikegap', models.CharField(default='', max_length=20)), ], ), ]
{"/myapp/views.py": ["/myapp/models.py"], "/myapp/tasks.py": ["/myapp/models.py", "/myproject/celery.py"]}
30,916,918
vinosa75/script
refs/heads/main
/myapp/migrations/0001_initial.py
# Generated by Django 3.1.6 on 2021-09-20 12:01 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='HistoryOIChange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.DateTimeField()), ('call1', models.CharField(default='', max_length=20)), ('call2', models.CharField(default='', max_length=20)), ('put1', models.CharField(default='', max_length=20)), ('put2', models.CharField(default='', max_length=20)), ('callstrike', models.CharField(max_length=20)), ('putstrike', models.CharField(max_length=20)), ('symbol', models.CharField(max_length=20)), ('expiry', models.DateField()), ], ), migrations.CreateModel( name='HistoryOITotal', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.DateTimeField()), ('call1', models.CharField(default='', max_length=20)), ('call2', models.CharField(default='', max_length=20)), ('put1', models.CharField(default='', max_length=20)), ('put2', models.CharField(default='', max_length=20)), ('callstrike', models.CharField(max_length=20)), ('putstrike', models.CharField(max_length=20)), ('symbol', models.CharField(max_length=20)), ('expiry', models.DateField()), ], ), migrations.CreateModel( name='LiveEquityResult', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.TimeField()), ('date', models.DateField(blank=True, null=True)), ('symbol', models.CharField(default='', max_length=20)), ('open', models.CharField(default='', max_length=20)), ('high', models.CharField(default='', max_length=20)), ('low', models.CharField(default='', max_length=20)), ('prev_day_close', models.CharField(default='', max_length=20)), ('ltp', models.CharField(max_length=20)), ('strike', models.CharField(max_length=20)), ], ), migrations.CreateModel( name='LiveOIChange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.DateTimeField()), ('call1', models.CharField(default='', max_length=20)), ('call2', models.CharField(default='', max_length=20)), ('put1', models.CharField(default='', max_length=20)), ('put2', models.CharField(default='', max_length=20)), ('callstrike', models.CharField(max_length=20)), ('putstrike', models.CharField(max_length=20)), ('symbol', models.CharField(max_length=20)), ('expiry', models.DateField()), ], ), migrations.CreateModel( name='LiveOITotal', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.DateTimeField()), ('call1', models.CharField(default='', max_length=20)), ('call2', models.CharField(default='', max_length=20)), ('put1', models.CharField(default='', max_length=20)), ('put2', models.CharField(default='', max_length=20)), ('callstrike', models.CharField(max_length=20)), ('putstrike', models.CharField(max_length=20)), ('symbol', models.CharField(max_length=20)), ('expiry', models.DateField()), ], ), migrations.CreateModel( name='LiveOITotalAllSymbol', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.DateTimeField()), ('call1', models.CharField(default='', max_length=20)), ('call2', models.CharField(default='', max_length=20)), ('put1', models.CharField(default='', max_length=20)), ('put2', models.CharField(default='', max_length=20)), ('callstrike', models.CharField(max_length=20)), ('putstrike', models.CharField(max_length=20)), ('symbol', models.CharField(max_length=20)), ('expiry', models.DateField()), ('callone', models.CharField(default='', max_length=20)), ('putone', models.CharField(default='', max_length=20)), ('callhalf', models.CharField(default='', max_length=20)), ('puthalf', models.CharField(default='', max_length=20)), ], ), ]
{"/myapp/views.py": ["/myapp/models.py"], "/myapp/tasks.py": ["/myapp/models.py", "/myproject/celery.py"]}
30,916,919
vinosa75/script
refs/heads/main
/myapp/migrations/0012_auto_20211011_0200.py
# Generated by Django 3.1.6 on 2021-10-11 02:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0011_livesegment_change_perc'), ] operations = [ migrations.AlterField( model_name='livesegment', name='date', field=models.DateField(), ), migrations.AlterField( model_name='livesegment', name='time', field=models.TimeField(), ), ]
{"/myapp/views.py": ["/myapp/models.py"], "/myapp/tasks.py": ["/myapp/models.py", "/myproject/celery.py"]}
30,916,920
vinosa75/script
refs/heads/main
/myapp/migrations/0014_livesegment_donetoday.py
# Generated by Django 3.2.8 on 2021-10-19 19:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0013_testequityresult'), ] operations = [ migrations.AddField( model_name='livesegment', name='doneToday', field=models.CharField(default='', max_length=10), ), ]
{"/myapp/views.py": ["/myapp/models.py"], "/myapp/tasks.py": ["/myapp/models.py", "/myproject/celery.py"]}
30,916,921
vinosa75/script
refs/heads/main
/myapp/migrations/0013_testequityresult.py
# Generated by Django 3.1.6 on 2021-10-14 01:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0012_auto_20211011_0200'), ] operations = [ migrations.CreateModel( name='TestEquityResult', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.TimeField()), ('date', models.DateTimeField()), ('symbol', models.CharField(default='', max_length=20)), ('open', models.CharField(default='', max_length=20)), ('high', models.CharField(default='', max_length=20)), ('low', models.CharField(default='', max_length=20)), ('prev_day_close', models.CharField(default='', max_length=20)), ('ltp', models.CharField(max_length=20)), ('strike', models.CharField(max_length=20)), ('opencrossed', models.CharField(default='', max_length=20)), ], ), ]
{"/myapp/views.py": ["/myapp/models.py"], "/myapp/tasks.py": ["/myapp/models.py", "/myproject/celery.py"]}
30,935,826
rohansh-tty/bamlight
refs/heads/master
/center_crop.py
from PIL import Image import os import argparse from collections import defaultdict from functools import wraps from time import perf_counter, localtime from datetime import datetime, timezone CROP_PATH = r'.\cropped_images' RESIZE_PATH = r'.\resize' JPG_PATH, PNG_PATH = r'.\jpg_images', r'.\png_images' IMAGE_DIRECTORY = r'.\images' invoke = False # validation tests def valid_path(path): if not os.path.isdir(path) or not isinstance(path, str): raise ValueError def valid_pct(pct): if pct < 0 or pct > 1: raise ValueError def valid_dim(dim): if isinstance(dim, tuple): for i in dim: if int(i)<0: raise ValueError else: for i in dim[0].split(','): if int(i)<0: raise ValueError func_reg = defaultdict(lambda : 0) def func_log(fn): ''' Decorator which holds on log details whenever input function is executed. Args: fn: A User-Defined Function Returns a inner function(callable) ''' count, total_time = 0, 0 @wraps(fn) def inner(*args, **kwargs): nonlocal count nonlocal total_time func_time = datetime.now(timezone.utc) func_id = hex(id(fn.__name__)) start_time = perf_counter() result = fn(*args, **kwargs) elapsed_time = perf_counter()-start_time func_reg[inner.__name__] = count count = count + 1 total_time = total_time + elapsed_time print(f'Function named {fn.__name__} with ID of {func_id} was executed at {func_time}\n Current Execution Time: {elapsed_time} seconds \n Total Execution Time: {total_time} seconds') return result return inner @func_log def crp_p(folder_path:str, dest_path, pct): valid_path(folder_path) valid_path(dest_path) valid_pct(pct) total_files = len(os.listdir(folder_path)) count = 0 for img in os.listdir(folder_path): name=img img = Image.open(os.path.join(folder_path, img)) w, h = img.size # new = Image.new('RGB', (w, h)) new_w, new_h = w*(1-pct), h*(1-pct) sizes = [] for i in range(0, max(w,h), 10): if i+max(new_w, new_h) < max(w,h): dim = (i, i, i+max(new_w, new_h), i+max(new_w, new_h)) try: new = img.crop(dim) new.save(os.path.join(dest_path, name)) except: print(f'<<< Cannot crop the {name} due size mismatch. >>>') print(f'IMAGE {name} CROPPED BY {dim} ') count += 1 if count == total_files: print(f'<<<CROPPED {total_files} FILES. SAVED TO {dest_path}>>>') else: print(f'<<<CROPPED {total_files-count} FILES. SAVED TO {dest_path}>>>') print('-'*60) def crp_px(folder_path:str, dest_path, dim): valid_path(folder_path) valid_path(dest_path) valid_dim(dim) count = 0 total_files = len(os.listdir(folder_path)) for img in os.listdir(folder_path): name=img img = Image.open(os.path.join(folder_path, img)) w, h = img.size # new = Image.new('RGB', (w, h)) # if len(dim)==4: new = img.crop(dim) new.save(os.path.join(dest_path, name)) try: new = img.crop(dim) new.save(os.path.join(dest_path, name)) except: print(f'<<< Cannot crop the {name} due size mismatch. >>>') print(f'IMAGE {name} CROPPED BY {dim} ') count += 1 if count == total_files: print(f'<<<CROPPED {total_files} FILES SAVED TO {dest_path}>>>') else: print(f'<<<CROPPED {total_files-count} FILES SAVED TO {dest_path}>>>') print('-'*60) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Function to crop images by pixels/percentage in bulk') parser.add_argument('--type', type=str, help='path to image directory') parser.add_argument('--value', nargs='+', help='dim/pct of image pixels to be cropped') parser.add_argument('--crop', type=str, nargs='+', help='path to image directory and final output directory') # type = ['percent', 'px'] args = parser.parse_args() type_ = args.type val = args.value l1= args.value[0].split(',') source_folder, dest_folder = [i for i in args.crop][0], [i for i in args.crop][1] print(f'\n[SOURCE FOLDER]: {source_folder}\n') print(f'[DESTINATION FOLDER]: {dest_folder}\n') if type_=='px': dim = tuple([int(i) for i in l1]) crp_px(source_folder, dest_folder, dim = val) else: pct = [float(i) for i in args.value][-1] crp_p(source_folder, dest_folder, pct = pct)
{"/test_session11.py": ["/center_crop.py", "/resize.py", "/convert.py"], "/__main__.py": ["/convert.py", "/resize.py", "/center_crop.py"]}
30,935,827
rohansh-tty/bamlight
refs/heads/master
/__main__.py
from PIL import Image import os import argparse import convert import resize import center_crop CROP_PATH = r'.\results\cropped_images' RESIZE_PATH = r'.\results\resized_images' IMAGE_DIRECTORY = r'.\images' J2P_DIRECTORY = r'.\results\j2p_images' P2J_DIRECTORY = r'.\results\p2j_images' for path in {CROP_PATH, RESIZE_PATH, J2P_DIRECTORY, P2J_DIRECTORY}: if not os.path.isdir(path): os.mkdir(path) convert.j2p(IMAGE_DIRECTORY, J2P_DIRECTORY) convert.p2j(IMAGE_DIRECTORY, P2J_DIRECTORY) resize.res_p(IMAGE_DIRECTORY, RESIZE_PATH, pct=0.8) resize.res_h(IMAGE_DIRECTORY, RESIZE_PATH, height=500) resize.res_w(IMAGE_DIRECTORY, RESIZE_PATH, width=500) center_crop.crp_px(IMAGE_DIRECTORY, CROP_PATH, dim=(0, 0, 224, 224)) # center_crop.center_crop_image(IMAGE_DIRECTORY, CROP_PATH, dim=(10,50,20,60))
{"/test_session11.py": ["/center_crop.py", "/resize.py", "/convert.py"], "/__main__.py": ["/convert.py", "/resize.py", "/center_crop.py"]}
30,984,856
maxwell-dev/maxwell-client-python
refs/heads/master
/maxwell/action.py
import json import maxwell.protocol.maxwell_protocol_pb2 as protocol_types class Action(object): def __init__(self, do_req, connection, loop): self.__do_req = do_req self.__connection = connection self.__loop = loop def __str__(self): return f"{{type: {self.type}, value: {self.value}, source: {self.source}}}" def __repr__(self): return self.__str__() @property def type(self): return self.__do_req.type @property def value(self): return json.loads(self.__do_req.value) @property def source(self): return self.__do_req.source def end(self, value): self.__loop.create_task( self.__connection.send(self.__build_do_rep(value)) ) def done(self, value): self.__loop.create_task( self.__connection.send(self.__build_do_rep(value)) ) def failed(self, code, desc = ""): if code < 1024: raise Exception(f"Code must be >=1024, but now ${code}.") self.__loop.create_task( self.__connection.send(self.__build_error_rep(code, desc)) ) def __build_do_rep(self, value): do_rep = protocol_types.do_rep_t() do_rep.value = json.dumps(value) do_rep.traces.extend(self.__do_req.traces) return do_rep def __build_error_rep(self, code, desc): error2_rep = protocol_types.error2_rep_t() error2_rep.code = code error2_rep.desc = json.dumps(desc) error2_rep.traces.extend(self.__do_req.traces) return error2_rep
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,857
maxwell-dev/maxwell-client-python
refs/heads/master
/maxwell/frontend.py
import asyncio import traceback import json import pycommons.logger import maxwell.protocol.maxwell_protocol_pb2 as protocol_types from maxwell.action import Action from maxwell.connection import Code from maxwell.connection import Event from maxwell.listenable import Listenable from maxwell.subscription_mgr import SubscriptionMgr from maxwell.msg_queue_mgr import MsgQueueMgr logger = pycommons.logger.get_instance(__name__) class Frontend(Listenable): # =========================================== # apis # =========================================== def __init__(self, master, connection_mgr, options, loop): super().__init__() self.__master = master self.__connection_mgr = connection_mgr self.__options = options self.__loop = loop self.__msg_queue_mgr = MsgQueueMgr( self.__options.get('queue_capacity') ) self.__subscribe_callbacks = {} self.__events = {} # {topic: not_full_event} self.__subscription_mgr = SubscriptionMgr() self.__loop.create_task(self.__connect_to_frontend()) self.__pull_tasks = {} self.__watch_callbacks = {} self.__watched_actions = set() self.__connection = None def close(self): self.__do_disconnect_from_frontend() def subscribe(self, topic, offset, callback): if self.__subscription_mgr.has_subscribed(topic): raise Exception(f"Already subscribed: topic: {topic}") self.__subscribe_callbacks[topic] = callback event = asyncio.Event(loop=self.__loop) event.set() self.__events[topic] = event self.__subscription_mgr.add_subscription(topic, offset) if self.__connection != None and self.__connection.is_open(): self.__new_pull_task(topic) def unsubscribe(self, topic): self.__delete_pull_task(topic) self.__subscription_mgr.delete_subscription(topic) self.__events.pop(topic) self.__subscribe_callbacks.pop(topic) self.__msg_queue_mgr.delete(topic) def recv(self, topic, limit): if not self.__subscription_mgr.has_subscribed(topic): raise Exception(f"Not subscribed yet: topic: {topic}") event = self.__events.get(topic) msg_queue = self.__msg_queue_mgr.get(topic) msgs = msg_queue.get(limit) if len(msgs) > 0: msg_queue.delete_to(msgs[-1].offset) event.set() # trigger not_full_event return msgs else: event.set() # trigger not_full_event return [] async def do(self, action): result = await self.__request(self.__build_do_req(action)) return json.loads(result.value) def watch(self, action_type, callback): self.__watched_actions.add(action_type) self.__watch_callbacks[action_type] = callback if self.__connection != None and self.__connection.is_open(): self.__loop.create_task(self.__ensure_watched(action_type)) def unwatch(self, action_type): self.__watched_actions.discard(action_type) self.__watch_callbacks.pop(action_type) if self.__connection != None and self.__connection.is_open(): self.__loop.create_task(self.__unwatch(action_type)) # =========================================== # connection management # =========================================== async def __connect_to_frontend(self): self.__do_connect_to_frontend( await self.__ensure_frontend_resolved() ) def __do_connect_to_frontend(self, endpoint): self.__connection \ = self.__connection_mgr.fetch(endpoint) self.__connection.add_listener( Event.ON_CONNECTED, self.__on_connect_to_frontend_done ) self.__connection.add_listener( (Event.ON_ERROR, Code.FAILED_TO_CONNECT), self.__on_connect_to_frontend_failed ) self.__connection.add_listener( Event.ON_DISCONNECTED, self.__on_disconnect_from_frontend_done ) self.__connection.add_listener( Event.ON_MESSAGE, self.__on_action ) def __do_disconnect_from_frontend(self): self.__connection.delete_listener( Event.ON_CONNECTED, self.__on_connect_to_frontend_done ) self.__connection.delete_listener( (Event.ON_ERROR, Code.FAILED_TO_CONNECT), self.__on_connect_to_frontend_failed ) self.__connection.delete_listener( Event.ON_DISCONNECTED, self.__on_disconnect_from_frontend_done ) self.__connection.delete_listener( Event.ON_MESSAGE, self.__on_action ) self.__connection_mgr.release(self.__connection) self.__connection = None def __on_connect_to_frontend_done(self): self.__loop.create_task(self.__pull_and_watch()) self.notify(Event.ON_CONNECTED) def __on_connect_to_frontend_failed(self, _code): self.__do_disconnect_from_frontend() self.__loop.call_later(1, self.__reconnect_to_frontend) def __on_disconnect_from_frontend_done(self): self.__delete_all_pull_tasks() self.notify(Event.ON_DISCONNECTED) def __reconnect_to_frontend(self): self.__loop.create_task(self.__connect_to_frontend()) async def __ensure_frontend_resolved(self): while True: try: return await self.__master.resolve_frontend(False) except Exception: logger.error( "Failed to resolve frontend: %s", traceback.format_exc() ) await asyncio.sleep(1) continue # =========================================== # core functions # =========================================== async def __pull_and_watch(self): self.__renew_all_pull_tasks() await self.__rewatch_all() def __renew_all_pull_tasks(self): self.__subscription_mgr.to_pendings() for topic, offset in self.__subscription_mgr.get_all_pendings(): self.__new_pull_task(topic) def __new_pull_task(self, topic): self.__delete_pull_task(topic) self.__pull_tasks[topic] = self.__loop.create_task( self.__repeat_pull(topic) ) def __delete_all_pull_tasks(self): for topic, task in self.__pull_tasks.items(): task.cancel() self.__pull_tasks.clear() def __delete_pull_task(self, topic): task = self.__pull_tasks.get(topic) if task != None: task.cancel() self.__pull_tasks.pop(topic, None) async def __repeat_pull(self, topic): while True: try: await self.__pull(topic) except asyncio.TimeoutError: logger.debug("Timeout triggered, pull again...") except Exception: logger.warning("Error occured: %s", traceback.format_exc()) await asyncio.sleep(1) async def __pull(self, topic): msg_queue = self.__msg_queue_mgr.get(topic) event = self.__events.get(topic) callback = self.__subscribe_callbacks.get(topic) offset = self.__subscription_mgr.get_doing(topic) pull_rep = await self.__request( self.__build_pull_req(topic, offset) ) msg_queue.put(pull_rep.msgs) self.__subscription_mgr.to_doing(topic, msg_queue.last_offset() + 1) try: callback(topic) except Exception: logger.error("Failed to notify: %s", traceback.format_exc()) if msg_queue.is_full(): logger.info( "Msg queue is full, waiting for consuming: " "topic: %s, last offset: %s", topic, msg_queue.last_offset() ) event.clear() await event.wait() async def __rewatch_all(self): for action_type in self.__watched_actions: await self.__ensure_watched(action_type) async def __ensure_watched(self, action_type): while True: try: await self.__request(self.__build_watch_req(action_type)) logger.info("Watched action_type: %s", action_type) break except Exception: logger.error("Failed to watch: %s", traceback.format_exc()) await asyncio.sleep(1) async def __unwatch(self, action_type): await self.__request(self.__build_unwatch_req(action_type)) def __on_action(self, action): if action.__class__ != protocol_types.do_req_t: logger.error("Ignored action: %s", action) return callback = self.__watch_callbacks.get(action.type) if callback != None: try: callback( Action(action, self.__connection, self.__loop) ) except Exception: logger.error("Failed to notify: %s", traceback.format_exc()) async def __request(self, msg): if self.__connection == None: raise Exception("Connection isn't open!") await self.__connection.wait_until_open() return await self.__connection.request(msg) # =========================================== # req builders # =========================================== def __build_auth_req(self): auth_req = protocol_types.auth_req_t() auth_req.token = "ignore" return auth_req def __build_pull_req(self, topic, offset): pull_req = protocol_types.pull_req_t() pull_req.topic = topic pull_req.offset = offset pull_req.limit = self.__options.get("get_limit") return pull_req def __build_do_req(self, action): do_req = protocol_types.do_req_t() do_req.type = action.get("type") do_req.value = json.dumps(action.get("value")) do_req.traces.add() return do_req def __build_watch_req(self, action_type): watch_req = protocol_types.watch_req_t() watch_req.type = action_type return watch_req def __build_unwatch_req(self, action_type): unwatch_req = protocol_types.unwatch_req_t() unwatch_req.type = action_type return unwatch_req
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,858
maxwell-dev/maxwell-client-python
refs/heads/master
/maxwell/connection.py
import enum import asyncio import websockets import traceback import pycommons.logger import maxwell.protocol.maxwell_protocol_pb2 as protocol_types import maxwell.protocol.maxwell_protocol as protocol from maxwell.listenable import Listenable logger = pycommons.logger.get_instance(__name__) class Code(enum.Enum): OK = 0 FAILED_TO_ENCODE = 1 FAILED_TO_SEND = 2 FAILED_TO_DECODE = 3 FAILED_TO_RECEIVE = 4 FAILED_TO_CONNECT = 5 FAILED_TO_DISCONNECT = 6 UNKNOWN_ERROR = 99 class Event(enum.Enum): ON_CONNECTING = 100 ON_CONNECTED = 101 ON_DISCONNECTING = 102 ON_DISCONNECTED = 103 ON_MESSAGE = 104 ON_ERROR = 1 class Connection(Listenable): # =========================================== # apis # =========================================== def __init__(self, endpoint, options, loop): super().__init__() self.__endpoint = endpoint self.__options = options self.__loop = loop self.__should_run = True self.__repeat_reconnect_task = None self.__repeat_ping_task = None self.__repeat_receive_task = None self.__last_ref = 0 self.__open_event = asyncio.Event(loop=self.__loop) self.__closed_event = asyncio.Event(loop=self.__loop) self.__arrived_events = {} self.__msgs = {} # exclude ping & pull msgs self.__active_time = 0 self.__websocket = None self.__closed_event.set() self.__add_repeat_reconnect_task() self.__add_repeat_ping_task() self.__add_repeat_receive_task() def close(self): self.__should_run = False self.__delete_repeat_receive_task() self.__delete_repeat_ping_task() self.__delete_repeat_reconnect_task() async def send(self, msg): await self.__send(msg) async def request(self, msg, timeout=10): ref = self.__next_ref() if msg.__class__ == protocol_types.do_req_t: msg.traces[0].ref = ref else: msg.ref = ref self.__arrived_events[ref] = asyncio.Event(loop=self.__loop) await self.__send(msg) event = self.__arrived_events.get(ref) try: await asyncio.wait_for(event.wait(), timeout) except Exception as e: raise e finally: self.__arrived_events.pop(ref) code, msg = self.__msgs.pop(ref) if code != Code.OK: logger.warning("Unexpected: code: %s; msg: %s", code, msg) raise Exception(code) return msg def is_open(self): return self.__websocket != None \ and self.__websocket.open == True async def wait_until_open(self): return await self.__open_event.wait() def get_endpoint(self): return self.__endpoint # =========================================== # tasks # =========================================== def __add_repeat_reconnect_task(self): if self.__repeat_reconnect_task is None: self.__repeat_reconnect_task = \ self.__loop.create_task(self.__repeat_reconnect()) def __add_repeat_ping_task(self): if self.__repeat_ping_task is None: self.__repeat_ping_task \ = self.__loop.create_task(self.__repeat_ping()) def __add_repeat_receive_task(self): if self.__repeat_receive_task is None: self.__repeat_receive_task \ = self.__loop.create_task(self.__repeat_receive()) def __delete_repeat_reconnect_task(self): if self.__repeat_reconnect_task is not None: self.__repeat_reconnect_task.cancel() self.__repeat_reconnect_task = None def __delete_repeat_ping_task(self): if self.__repeat_ping_task is not None: self.__repeat_ping_task.cancel() self.__repeat_ping_task = None def __delete_repeat_receive_task(self): if self.__repeat_receive_task is not None: self.__repeat_receive_task.cancel() self.__repeat_receive_task = None # =========================================== # internal coroutines # =========================================== async def __repeat_reconnect(self): while self.__should_run: await self.__closed_event.wait() await self.__disconnect() await self.__connect() async def __repeat_ping(self): while self.__should_run: await self.__open_event.wait() await self.__ping() await asyncio.sleep(self.__options.get('ping_interval')) async def __repeat_receive(self): while self.__should_run: await self.__open_event.wait() await self.__recv() async def __ping(self): if self.__websocket != None: await self.__send(protocol_types.ping_req_t()) async def __connect(self): try: self.__on_connecting() self.__websocket = await websockets.connect( uri=self.__build_url(self.__endpoint), ping_interval=None, max_size=None ) self.__open_event.set() self.__closed_event.clear() self.__on_connected() except Exception: logger.error("Failed to connect: %s", traceback.format_exc()) self.__on_error(Code.FAILED_TO_CONNECT) if self.__should_run: await asyncio.sleep(self.__options.get("reconnect_delay")) await self.__connect() async def __disconnect(self): try: if self.__websocket is not None: self.__on_disconnecting() await self.__websocket.close() self.__on_disconnected() except Exception: logger.error("Failed to disconnect: %s", traceback.format_exc()) self.__on_error(Code.FAILED_TO_DISCONNECT) finally: self.__open_event.clear() self.__closed_event.set() async def __send(self, msg): encoded_msg = None try: encoded_msg = protocol.encode_msg(msg) except Exception: logger.error("Failed to encode: %s", traceback.format_exc()) self.__on_error(Code.FAILED_TO_ENCODE) try: if encoded_msg: await self.__websocket.send(encoded_msg) except Exception: logger.error("Failed to send: %s", traceback.format_exc()) self.__on_error(Code.FAILED_TO_SEND) async def __recv(self): try: encoded_msg = await self.__websocket.recv() except websockets.ConnectionClosed: logger.warning("Connection closed: endpoint: %s", self.__endpoint) self.__open_event.clear() self.__closed_event.set() return except Exception as e: logger.error("Failed to recv: %s", traceback.format_exc()) self.__on_error(Code.FAILED_TO_RECEIVE) return try: msg = protocol.decode_msg(encoded_msg) if msg.__class__ != protocol_types.ping_rep_t: self.__on_msg(msg) except Exception: logger.error("Failed to decode: %s", traceback.format_exc()) self.__on_error(Code.FAILED_TO_DECODE) # =========================================== # listeners # =========================================== def __on_connecting(self): logger.info("Connecting to endpoint: %s", self.__endpoint) self.notify(Event.ON_CONNECTING) def __on_connected(self): logger.info("Connected to endpoint: %s", self.__endpoint) self.notify(Event.ON_CONNECTED) def __on_disconnecting(self): logger.debug("Disconnecting from endpoint: %s", self.__endpoint) self.notify(Event.ON_DISCONNECTING) def __on_disconnected(self): logger.debug("Disconnected from endpoint: %s", self.__endpoint) self.notify(Event.ON_DISCONNECTED) def __on_error(self, code): logger.debug("Error occured: %s", code) self.notify(Event.ON_ERROR, code) self.notify((Event.ON_ERROR, code), code) def __on_msg(self, msg): msg_type = msg.__class__ if msg_type == protocol_types.do_req_t: self.notify(Event.ON_MESSAGE, msg) return if msg_type == protocol_types.do_rep_t \ or msg_type == protocol_types.ok2_rep_t \ or msg_type == protocol_types.error2_rep_t: ref = msg.traces[0].ref else: ref = msg.ref event = self.__arrived_events.get(ref) if event == None: logger.error("Failed to find event: msg: %s", msg) return if msg_type == protocol_types.error_rep_t \ or msg_type == protocol_types.error2_rep_t: self.__msgs[ref] = (msg.code, msg.desc) else: self.__msgs[ref] = (Code.OK, msg) event.set() # =========================================== # utils # =========================================== def __next_ref(self): new_ref = self.__last_ref + 1 if new_ref > 600000: new_ref = 1 self.__last_ref = new_ref return new_ref def __build_url(self, endpoint): return "ws://" + endpoint
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,859
maxwell-dev/maxwell-client-python
refs/heads/master
/maxwell/doer.py
class Doer(object): def __init__(self, frontend): self.__frontend = frontend async def do(self, action): return await self.__frontend.do(action)
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,860
maxwell-dev/maxwell-client-python
refs/heads/master
/maxwell/client.py
import asyncio import pycommons.logger from maxwell.connection_mgr import ConnectionMgr from maxwell.master import Master from maxwell.frontend import Frontend from maxwell.subscriber import Subscriber from maxwell.publisher import Publisher from maxwell.doer import Doer from maxwell.watcher import Watcher logger = pycommons.logger.get_instance(__name__) class Client(object): # =========================================== # APIs # =========================================== def __init__(self, endpoints, options=None, loop=None): self.__endpoints = endpoints self.__init_options(options) self.__init_loop(loop) self.__init_connection_mgr() self.__init_master() self.__publisher = None self.__frontend = None self.__subscriber = None self.__doer = None self.__watcher = None def close(self): self.__connection_mgr.clear() self.__master.close() if self.__frontend != None: self.__frontend.close() if self.__publisher != None: self.__publisher.close() def get_master(self): return self.__master def get_publisher(self): self.__ensure_publisher_inited() return self.__publisher def get_frontend(self): self.__ensure_frontend_inited() return self.__frontend def get_subscriber(self): self.__ensure_subscriber_inited() return self.__subscriber def get_doer(self): self.__ensure_doer_inited() return self.__doer def get_watcher(self): self.__ensure_watcher_inited() return self.__watcher # =========================================== # Init functions # =========================================== def __init_options(self, options): options = options if options else {} # if options.get('check_interval') == None: # options['check_interval'] = 1 if options.get('reconnect_delay') == None: options['reconnect_delay'] = 1 if options.get('ping_interval') == None: options['ping_interval'] = 10 # if options.get('max_idle_period') == None: # options['max_idle_period'] = 15 if options.get('default_round_timeout') == None: options['default_round_timeout'] = 5 if options.get('default_offset') == None: options['default_offset'] = -600 if options.get('get_limit') == None: options['get_limit'] = 64 if options.get('queue_capacity') == None: options['queue_capacity'] = 512 self.__options = options def __init_loop(self, loop): self.__loop = loop if loop else asyncio.get_event_loop() def __init_connection_mgr(self): self.__connection_mgr = ConnectionMgr(self.__options, self.__loop) def __init_master(self): self.__master = Master( self.__endpoints, self.__connection_mgr, self.__options, self.__loop ) def __ensure_publisher_inited(self): if self.__publisher != None: return self.__publisher = Publisher( self.__master, self.__connection_mgr, self.__options, self.__loop ) def __ensure_frontend_inited(self): if self.__frontend != None: return self.__frontend = Frontend( self.__master, self.__connection_mgr, self.__options, self.__loop ) def __ensure_subscriber_inited(self): if self.__subscriber != None: return self.__ensure_frontend_inited() self.__subscriber = Subscriber(self.__frontend) def __ensure_doer_inited(self): if self.__doer != None: return self.__ensure_frontend_inited() self.__doer = Doer(self.__frontend) def __ensure_watcher_inited(self): if self.__watcher != None: return self.__ensure_frontend_inited() self.__watcher = Watcher(self.__frontend)
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,861
maxwell-dev/maxwell-client-python
refs/heads/master
/test/subscriber_test.py
import asyncio import pycommons.logger from maxwell.client import Client logger = pycommons.logger.get_instance(__name__) client = None async def repeat_recv(): loop = asyncio.get_event_loop() client = Client(["localhost:8081", "localhost:8082"], loop=loop) subscriber = client.get_subscriber() def on_message(topic): logger.debug("Received topic: %s", topic) while True: msgs = subscriber.recv("topic_0", 8) values = [int.from_bytes(msg.value, byteorder='little') for msg in msgs] logger.debug("************Recevied msgs: %s", values) if len(msgs) < 8: break subscriber.subscribe("topic_0", 0, on_message) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.create_task(repeat_recv()) loop.run_forever()
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,862
maxwell-dev/maxwell-client-python
refs/heads/master
/maxwell/watcher.py
class Watcher(object): def __init__(self, frontend): self.__frontend = frontend def watch(self, action_type, callback): self.__frontend.watch(action_type, callback) def unwatch(self, action_type): self.__frontend.unwatch(action_type)
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,863
maxwell-dev/maxwell-client-python
refs/heads/master
/test/master_test.py
import asyncio import pycommons.logger from maxwell.client import Client logger = pycommons.logger.get_instance(__name__) if __name__ == '__main__': loop = asyncio.get_event_loop() client = Client(["localhost:8081", "localhost:8082"], loop=loop) master = client.get_master() endpoint = loop.run_until_complete(asyncio.ensure_future(master.resolve_frontend())) logger.info("endpoint: %s", endpoint) endpoint = loop.run_until_complete(asyncio.ensure_future(master.resolve_backend("topic_0"))) logger.info("endpoint: %s", endpoint) loop.run_forever()
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,864
maxwell-dev/maxwell-client-python
refs/heads/master
/maxwell/subscriber.py
class Subscriber(object): def __init__(self, frontend): self.__frontend = frontend def subscribe(self, topic, offset, callback): self.__frontend.subscribe(topic, offset, callback) def unsubscribe(self, topic): self.__frontend.unsubscribe(topic) def recv(self, topic, limit): return self.__frontend.recv(topic, limit)
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,865
maxwell-dev/maxwell-client-python
refs/heads/master
/test/publisher_test.py
import asyncio import time import traceback import pycommons.logger from maxwell.client import Client logger = pycommons.logger.get_instance(__name__) async def repeat_publish(): client = Client(["localhost:8081", "localhost:8082"], loop=loop) publisher = client.get_publisher() while True: value = int(time.time()) logger.debug("************Publish msg: %s", value) try: await publisher.publish( "topic_3", value.to_bytes(8, byteorder='little') ) except Exception: logger.error("Failed to encode: %s", traceback.format_exc()) await asyncio.sleep(1) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.create_task(repeat_publish()) loop.run_forever()
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,866
maxwell-dev/maxwell-client-python
refs/heads/master
/test/doer_test.py
import asyncio import traceback import pycommons.logger from maxwell.client import Client logger = pycommons.logger.get_instance(__name__) client = None async def do(): loop = asyncio.get_event_loop() client = Client(["localhost:8081"], loop=loop) doer = client.get_doer() while True: logger.debug("doing.... ") try: result = await doer.do({ "type": 'get_candles', "value": { "signatures": { "default": "candle", }, "topic": { "exchange": "huobi", "quote_currency": "usdt", "base_currency": "btc", "timeframe": "1m", }, "start_ts": 1545293880, "end_ts": 1545295020 } }) logger.debug("result: %s", result) except Exception: logger.error("Failed to check: %s", traceback.format_exc()) await asyncio.sleep(5) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.create_task(do()) loop.run_forever()
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,867
maxwell-dev/maxwell-client-python
refs/heads/master
/test/watcher_test.py
import asyncio import pycommons.logger from maxwell.client import Client logger = pycommons.logger.get_instance(__name__) async def repeat_recv(): loop = asyncio.get_event_loop() client = Client(["localhost:8081"], loop=loop) watcher = client.get_watcher() def receive(action): logger.debug("Received action: %s", action) action.end("nothing") watcher.watch("get_candles", receive) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.create_task(repeat_recv()) loop.run_forever()
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,868
maxwell-dev/maxwell-client-python
refs/heads/master
/setup.py
import setuptools import subprocess cmd = ['pip', 'install', '-r', 'requirements.txt'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) for line in p.stdout: print(line) p.wait() with open("README.md", "r") as f: long_description = f.read() setuptools.setup( name="maxwell_client", version="0.1.0", author="Xu Chaoqian", author_email="chaoranxu@gmail.com", description="The maxwell client implementation for python.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/maxwell-dev/maxwell-client-python", packages=setuptools.find_packages(), classifiers=( "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ) )
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,869
maxwell-dev/maxwell-client-python
refs/heads/master
/maxwell/publisher.py
import pycommons.logger import maxwell.protocol.maxwell_protocol_pb2 as protocol_types logger = pycommons.logger.get_instance(__name__) class Publisher(object): # =========================================== # apis # =========================================== def __init__(self, master, connection_mgr, options, loop): self.__master = master self.__connection_mgr = connection_mgr self.__options = options self.__loop = loop self.__connections = {} def close(self): for connection in self.__connections.values(): self.__disconnect_from_backend(connection) async def publish(self, topic, value): endpoint = await self.__master.resolve_backend(topic) connection = self.__connect_to_backend(endpoint) await self.__publish(connection, topic, value) # =========================================== # connector # =========================================== def __connect_to_backend(self, endpoint): connection = self.__connections.get(endpoint) if connection == None: connection = self.__connection_mgr.fetch(endpoint) self.__connections[endpoint] = connection return connection def __disconnect_from_backend(self, endpoint): connection = self.__connections.pop(endpoint, None) if connection != None: self.__connection_mgr.release(connection) # =========================================== # internal coros # =========================================== async def __publish(self, connection, topic, value): await connection.wait_until_open() await connection.request( self.__build_publish_req(topic, value) ) # =========================================== # req builders # =========================================== def __build_publish_req(self, topic, value): push_req = protocol_types.push_req_t() push_req.topic = topic push_req.value = value return push_req
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
30,984,870
maxwell-dev/maxwell-client-python
refs/heads/master
/maxwell/master.py
import asyncio import pycommons.logger import maxwell.protocol.maxwell_protocol_pb2 as protocol_types from maxwell.connection import Code from maxwell.connection import Event logger = pycommons.logger.get_instance(__name__) class Master(object): # =========================================== # apis # =========================================== def __init__(self, endpoints, connection_mgr, options, loop): self.__endpoints = endpoints self.__connection_mgr = connection_mgr self.__options = options self.__loop = loop self.__endpoint_index = -1 self.__frontend_endpoint = None self.__backend_endpoints = {} self.__open_event = asyncio.Event(loop=self.__loop) self.__connection = None self.__connect_to_master() def close(self): self.__disconnect_from_master() async def resolve_frontend(self, cache=True): if cache: if self.__frontend_endpoint != None: return self.__frontend_endpoint return await self.__resolve_frontend() async def resolve_backend(self, topic, cache=True): if cache: endpoint = self.__backend_endpoints.get(topic) if endpoint != None: return endpoint return await self.__resolve_backend(topic) # =========================================== # connector # =========================================== def __connect_to_master(self): self.__connection = self.__connection_mgr.fetch( self.__next_endpoint() ) self.__connection.add_listener( Event.ON_CONNECTED, self.__on_connect_to_master_done ) self.__connection.add_listener( (Event.ON_ERROR, Code.FAILED_TO_CONNECT), self.__on_connect_to_master_failed ) def __disconnect_from_master(self): self.__connection.delete_listener( Event.ON_CONNECTED, self.__on_connect_to_master_done ) self.__connection.delete_listener( (Event.ON_ERROR, Code.FAILED_TO_CONNECT), self.__on_connect_to_master_failed ) self.__connection_mgr.release(self.__connection) self.__connection = None def __on_connect_to_master_done(self): self.__open_event.set() def __on_connect_to_master_failed(self, _code): self.__open_event.clear() self.__disconnect_from_master() self.__loop.call_later(1, self.__connect_to_master) # =========================================== # internal coroutines # =========================================== async def __resolve_frontend(self): resolve_frontend_rep = await self.__request( self.__build_resolve_frontend_req() ) self.__frontend_endpoint = resolve_frontend_rep.endpoint return self.__frontend_endpoint async def __resolve_backend(self, topic): resolve_backend_rep = await self.__request( self.__build_resolve_backend_req(topic) ) self.__backend_endpoints[topic] = resolve_backend_rep.endpoint return resolve_backend_rep.endpoint async def __request(self, action): await self.__open_event.wait() return await self.__connection.request(action) # =========================================== # req builders # =========================================== def __build_resolve_frontend_req(self): resolve_frontend_req = protocol_types.resolve_frontend_req_t() return resolve_frontend_req def __build_resolve_backend_req(self, topic): resolve_backend_req = protocol_types.resolve_backend_req_t() resolve_backend_req.topic = topic return resolve_backend_req # =========================================== # urls # =========================================== def __next_endpoint(self): self.__endpoint_index += 1 if self.__endpoint_index >= len(self.__endpoints): self.__endpoint_index = 0 return self.__endpoints[self.__endpoint_index]
{"/maxwell/client/client.py": ["/maxwell/client/logger.py", "/maxwell/client/connection_mgr.py", "/maxwell/client/master.py", "/maxwell/client/frontend.py"], "/test/master_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/msg_queue_mgr.py": ["/maxwell/client/msg_queue.py"], "/maxwell/client/listenable.py": ["/maxwell/client/logger.py"], "/test/subscriber_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py", "/maxwell/client.py"], "/maxwell/client/master.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py"], "/test/request_test.py": ["/maxwell/client/logger.py", "/maxwell/client/client.py"], "/maxwell/client/connection_mgr.py": ["/maxwell/client/connection.py"], "/maxwell/client/frontend.py": ["/maxwell/client/logger.py", "/maxwell/client/connection.py", "/maxwell/client/listenable.py", "/maxwell/client/subscription_mgr.py", "/maxwell/client/msg_queue_mgr.py"], "/maxwell/frontend.py": ["/maxwell/action.py", "/maxwell/connection.py"], "/maxwell/client.py": ["/maxwell/master.py", "/maxwell/frontend.py", "/maxwell/subscriber.py", "/maxwell/publisher.py", "/maxwell/doer.py", "/maxwell/watcher.py"], "/test/publisher_test.py": ["/maxwell/client.py"], "/test/doer_test.py": ["/maxwell/client.py"], "/test/watcher_test.py": ["/maxwell/client.py"], "/maxwell/master.py": ["/maxwell/connection.py"]}
31,051,205
JordiEspinozaMendoza/simulation-web
refs/heads/main
/backend/base/views/frequency_views.py
from django.shortcuts import render from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from rest_framework import status from base.scripts.frequency import TestFrequency from base.scripts.generator import CallGenerator import pandas as pd @api_view(["GET"]) def callTestFrequency(request): data = request.data # testNumbers = [] # for i in data["df"]: # testNumbers.append(int(i)) data_generator = {"n": [], "Xn": [], "Xn+1": [], "Rn": []} CallGenerator(17, 101, 221, 17001, 0, False, [], data_generator) # ? We declare a object of the class TestFrequency testFrequency = TestFrequency( int(data["numberGroups"]), float(data["alpha"]), data_generator ) dfFrequency, foundedChiFreq, chiFreq, dfFreq = testFrequency.solve() response = { "dfFrequency": dfFrequency, "foundedChiFrequency": foundedChiFreq, "chiFrequency": chiFreq, "dfFrequency": dfFreq, } return Response(response, status=status.HTTP_200_OK)
{"/base/scripts/smirnov.py": ["/base/scripts/generator.py"], "/base/views/generator_views.py": ["/base/scripts/generator.py"], "/base/scripts/frequency.py": ["/base/scripts/generator.py", "/base/scripts/tableChi.py"], "/base/views/frequency_views.py": ["/base/scripts/frequency.py", "/base/scripts/generator.py"], "/base/views/smirnov_views.py": ["/base/scripts/smirnov.py", "/base/scripts/generator.py"], "/backend/base/views/frequency_views.py": ["/base/scripts/frequency.py", "/base/scripts/generator.py"]}
31,203,415
Tuhtarov/fdict
refs/heads/main
/fcore.py
import os class Filter: _BREAK_LINE_SYMBOL = int(len('\n')) def __init__(self, origin_path: str, destination_path: str = '', qty_symbols: int = 8): self._origin = origin_path self._qty_symbols = qty_symbols sep = os.sep segments_origin_path = origin_path.split(sep) file_name_filtered = 'filtered_' + segments_origin_path.pop() if destination_path == '': self._destination = sep.join(segments_origin_path) + sep + file_name_filtered else: self._destination = destination_path + sep + file_name_filtered def run(self): self._run_specify_encode(encoding='utf-8') def _run_specify_encode(self, encoding: str): print('filtration started... \n') with open(self._origin, encoding=encoding) as origin: with open(self._destination, 'w', encoding=encoding) as destination: old_qty = 0 new_qty = 0 try: for line in origin: old_qty = old_qty + 1 if len(line) >= (self._qty_symbols + self._BREAK_LINE_SYMBOL): destination.writelines(line) new_qty = new_qty + 1 print(f'\nqty lines in source file == {old_qty}') print(f'qty lines in new file == {new_qty}') print("\nI'm tired, but I did my job\n") except UnicodeDecodeError: print('\\ 0_0 /\n\ndanger word --> ' + str(line) + f'encoding error in {old_qty} line\n') response_on_error = input('would you like to specify a different encoding? y/n \n') if response_on_error.lower() == 'y': user_encoding = str(input("\ntype your encoding (example: 'latin-1') => ")) user_encoding = user_encoding.replace("'", '').replace('"', '') self._run_specify_encode(user_encoding) else: exit('\nBye :(') origin.close() destination.close()
{"/fcore/worker.py": ["/fcore/filter.py"], "/fcore/controller.py": ["/fcore/worker.py", "/fcore/functional.py", "/fcore/filter.py"], "/fcore/functional.py": ["/fcore/worker.py", "/fcore/filter.py"], "/fdict.py": ["/fcore/controller.py", "/fcore.py"]}
31,203,416
Tuhtarov/fdict
refs/heads/main
/fdict.py
import os.path from fcore import Filter # это пэт проект начинающего разраба # вся суть данной приложухи заключается в фильтрации словаря (файла с паролями) по заданным критериям # # пример использования: есть большой файл > 1000 строк, стандартные пароли для WPA-2 сетей начинаются с 8 символов, # но зачастую, в словарях с интернета много строк, где количество символов < 8, что затрудняет работу утилиты "hashcat" # # алгоритм фильтрации таков: открывается словарь, создаётся дополнительный файл в родительском каталоге открытого файла # в этот дополнительный файл, строчкой за строчкой, помеющатся строки с указанной длинной символов. delimiter = '===================================' print('') print(delimiter) print("+=============RUNNING=============+") print(delimiter) file_path = '' qty_symbols = 8 DEFAULT_QTY_NUM = 8 def get_file_path(): global file_path file_path = str(input("\nType full path of file => ")) get_file_path() def check_file_path(f_path): if not os.path.exists(f_path): return 'path not exists' if not os.path.isfile(f_path): return 'this not file' return 'ok' while check_file_path(file_path) != 'ok': print(check_file_path(file_path)) print("please, type the correct path") get_file_path() else: print('ok.. file is correct!\n') def get_digit(): global qty_symbols try: qty_symbols = int(input("type min. qty symbols in lines => ")) except ValueError: print('you entered incorrect value. Please type correct digit') get_digit() return qty_symbols get_digit() if not qty_symbols >= DEFAULT_QTY_NUM: response = input(f'your qty symbols ({qty_symbols}) for lines is small (normal = {DEFAULT_QTY_NUM}). ' f'you want change qty? y/n \n') if response == 'Y' or response == 'y': get_digit() filter_core = Filter(origin_path=file_path, qty_symbols=qty_symbols) filter_core.run() print(delimiter) print('---> The end. Bye :)\n') print("---> developer: 'Tukhtarov Dynamic'") print(delimiter)
{"/fcore/worker.py": ["/fcore/filter.py"], "/fcore/controller.py": ["/fcore/worker.py", "/fcore/functional.py", "/fcore/filter.py"], "/fcore/functional.py": ["/fcore/worker.py", "/fcore/filter.py"], "/fdict.py": ["/fcore/controller.py", "/fcore.py"]}
31,253,577
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/views.py
from django.conf import settings from django.shortcuts import render, redirect from django.urls import reverse_lazy, reverse from django.http import JsonResponse, HttpResponse from django.contrib.auth.models import User from .models import Student, Hint, Stats, Group, Laboratory, File, Teacher, EducationControl from django.views.generic.edit import CreateView, UpdateView from django.views.generic import ListView from .forms import LabForm, AuthUserForm, RegisterUserForm, ChangePasswordForm, FileForm, EditTeacherInformationForm from django.contrib.auth.views import LoginView, LogoutView, PasswordChangeView from django.contrib.auth import update_session_auth_hash ''' import sys import os import subprocess import shutil import pathlib from pathlib import Path import os.path import argparse ''' ''' def open_code(request, res_file, check_file, student_name, lab_numb, lab_exp): """ res_file - ссылка на дерикторию, где лежат входные и выходные данные проверки check_file - ссылка на личную аудиторию студента student_name - имя студента lub_num - номер лыбы lab_exp - расширение файла """ #parser = argparse.ArgumentParser(description='enter the key directories') #parser.add_argument('res', type=str, help='enter the directory with the files to res') #parser.add_argument('files_student', type=str, help='enter the directory with the students file') #parser.add_argument('last_name', type=str, help='enter the students last name') #parser.add_argument('lab_number', type=str, help='enter the lab number') #parser.add_argument('lab_expansion', type=str, help='enter the extension') #args = parser.parse_args() #a = settings.BASE_DIR main = settings.BASE_DIR resFile = os.path.join(res_file) checkFile = os.path.join(check_file) studentName = os.path.join(student_name) labNum = os.path.join(lab_numb) labExp = os.path.join(lab_exp) #name_files = (args.last_name + '_' + args.lab_number + args.lab_expansion) #files_student = os.path.join(args.files_student, name_files) files_copy1 = os.path.join(checkFile,'input.in.txt') files_copy2 = os.path.join(checkFile,'input.secret.txt') files_insert = os.path.join(main,'input.txt') # # # def Checking_Hashes1(check,main): # f = open(os.path.join(res_file, 'output.out.txt'), "r") # f2 = open(os.path.join(main, 'output.txt'), "r") # global percent # percent=0 # while True: # answer_teacher1=hash(f.readline()) # answer_student1=hash(f2.readline()) # if answer_teacher1==answer_student1: # percent=percent+10 # if not answer_student1: # break # f.close() # f2.close() # # def Checking_Hashes2(check,main): # f = open(os.path.join(res_file, 'output.secret.txt'), "r") # f2 = open(os.path.join(main, 'output.txt'), "r") # global percent2 # percent2=0 # while True: # answer_teacher1=hash(f.readline()) # answer_student1=hash(f2.readline()) # if answer_teacher1==answer_student1: # percent2=percent2+10 # if not answer_student1: # break # f.close() # f2.close() # # # shutil.copyfile(files_copy1,files_insert) # print ('..................copy file true.................') # subprocess.call([sys.executable,checkFile]) # print ('.........................Launch file true.........................') # Checking_Hashes1(check,main) # print ('......................Checking files hashes 1 true................') # shutil.copyfile(files_copy2,files_insert) # print ('....................Copy file true..................') # launchFile(files_student) # print ('........................Launch file true..........................') # Checking_Hashes2(check,main) # print ('.........................Checking files hashes 2 true...............') # print ('.........................',percent+percent2,'...............') # os.remove(os.path.join(main,'input.txt')) # os.remove(os.path.join(main,'output.txt')) # # ''' """ Функция вывода главной страницы """ class facePage(ListView): model = Student template_name='botbi20i1/face_page.html' context_object_name = 'students' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['groups'] = Group.objects.all() context['teachers'] = Teacher.objects.all() context['stats'] = Stats.objects.all().order_by('lab') return context """ Страница пользователя """ class userPage(ListView): model = Student template_name='botbi20i1/user_page.html' context_object_name = 'students' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['groups'] = Group.objects.all() context['teachers'] = Teacher.objects.all() context['stats'] = Stats.objects.all() return context class LoginUserView(LoginView): template_name = 'botbi20i1/login_page.html' form_class = AuthUserForm success_url = 'face_page' def get_success_url(self): return self.success_url class Logout(LogoutView): next_page = '' class RegisterUserView(CreateView): model = User form_class = RegisterUserForm template_name = 'botbi20i1/register_page.html' success_msg = 'Пользователь создан' success_url = 'face_page' def get_success_url(self): return self.success_url def ChangePasswordView(request): if request.user.is_authenticated: if request.method == 'POST': fm = ChangePasswordForm(user=request.user, data=request.POST) if fm.is_valid(): fm.save() update_session_auth_hash(request, fm.user) return redirect('face_page') else: fm = ChangePasswordForm(user=request.user) context = { 'form': fm } return render(request, template_name='botbi20i1/changepassword_page.html', context=context) else: return redirect('face_page') """ Страница группы """ def group(request, group_id): students = Student.objects.filter(group_id__id=group_id).order_by('second_name') print(students) stats = Stats.objects.all().order_by('lab') teachers = Teacher.objects.all() KT_1 = EducationControl.objects.filter(group__id=group_id ,number=1) KT_2 = EducationControl.objects.filter(group__id=group_id ,number=2) KT_3 = EducationControl.objects.filter(group__id=group_id ,number=3) teachr = '' studnt = '' for teacher in teachers: if request.user.id == teacher.user.id: teachr = teacher for student in students: if request.user.id == student.user.id: studnt = student context = { 'teachers': teachers, 'teachr': teachr, 'kt_1': KT_1[0], 'kt_2': KT_2[0], 'kt_3': KT_3[0], 'students': students, 'studnt': studnt, 'stats': stats, } return render(request, template_name='botbi20i1/group_page.html', context=context) """ Функция вывода страницы лабы """ def labsPage(request, id): student = Student.objects.filter(user=request.user) labs = Laboratory.objects.filter(pk=id) print(labs) files = File.objects.filter(student=student[0], lab=labs[0]) print(files) for lab in labs: if lab.id == id: lab = lab if not files: file = '' else: file = files[0] context = { 'labs': labs, 'student': student, 'file': file, 'lab': lab } return render(request, template_name='botbi20i1/labs_page.html', context=context) """ Функция вывода страницы студента с лабораторными работами (Для преподователя) """ def studentPage(request, id): student = Student.objects.filter(user_id=id) stats = Stats.objects.filter(student=student[0]) files = File.objects.filter(student=student[0]) for file in files: print(file.lab.name) if not files: file = '' else: files = files context = { 'stats': stats, 'student': student[0], 'files': files, } return render(request, template_name='botbi20i1/student_page.html', context=context) def index(request, index_id): data = {} students = Student.objects.filter(group_id__id=index_id) for student in students: data.update({str(student.personal_number): {'name': student.name, 'rating': student.rating, 'labs': {}}}) i = 1 labs = Stats.objects.filter(student=student, status=False).prefetch_related('lab') for lab in labs: data[str(student.personal_number)]['labs'].update({ i: { 'name': lab.lab.name, 'description': lab.lab.description, 'status': int(lab.status), 'hints': {} } }) hints = Hint.objects.filter(lab=lab.lab.id) j = 1 for hint in hints: data[str(student.personal_number)]['labs'][i]['hints'].update({j: hint.text}) j += 1 i += 1 return JsonResponse(data) """ Функция изменения статуса лабы, при нажати на radio-button, и изменения рейтинга студента """ def update_changes(request): if request.GET: stats = Stats.objects.get(pk=request.GET['stats_id']) user = Student.objects.get(pk=stats.student.id) labs_kt1 = user.labs.filter(kt=1) labs_kt2 = user.labs.filter(kt=2) labs_kt3 = user.labs.filter(kt=3) KT_number = stats.lab.kt kt = EducationControl.objects.filter(number=KT_number) if request.GET['status'] == '1': if user.rating_1KT <= 100 and user.rating_2KT <= 100 and user.rating_3KT <= 100: if KT_number == 1: for lab_kt1 in labs_kt1: if lab_kt1 == stats.lab: ratingPoint = (lab_kt1.weight / 100) * kt[0].weight if stats.status == True: stats.status = False stats.save() if user.rating_1KT > 0: user.rating_1KT -= lab_kt1.weight user.rating -= ratingPoint else: stats.status = True stats.save() if user.rating_1KT >= 0: user.rating_1KT += lab_kt1.weight user.rating += ratingPoint elif KT_number == 2: for lab_kt2 in labs_kt2: if lab_kt2 == stats.lab: ratingPoint = (lab_kt2.weight / 100) * kt[0].weight if stats.status == True: stats.status = False stats.save() if user.rating_2KT > 0: user.rating_2KT -= lab_kt2.weight user.rating -= ratingPoint else: stats.status = True stats.save() if user.rating_2KT >= 0: user.rating_2KT += lab_kt2.weight user.rating += ratingPoint else: for lab_kt3 in labs_kt3: if lab_kt3 == stats.lab: ratingPoint = (lab_kt3.weight / 100) * kt[0].weight if stats.status == True: stats.status = False stats.save() if user.rating_3KT > 0: user.rating_3KT -= lab_kt3.weight user.rating -= ratingPoint else: stats.status = True stats.save() if user.rating_3KT >= 0: user.rating_3KT += lab_kt3.weight user.rating += ratingPoint if user.rating < 0: user.rating = 0 user.save() stats.save() return JsonResponse( { 'status': stats.status, 'user_id': user.id, 'lab_id': request.GET['stats_id'], 'kt_1': float('{:.2f}'.format(user.rating_1KT)), 'kt_2': float('{:.2f}'.format(user.rating_2KT)), 'kt_3': float('{:.2f}'.format(user.rating_3KT)), 'rating': float('{:.2f}'.format(user.rating)) }) def view_info(request): student = Student.objects.filter(user=request.user) files = File.objects.filter(student=student[0]) print(files[0].student) url = "/media/GroupProject.py" context = { 'url': url, 'files': files } return render(request, template_name='botbi20i1/info.html', context=context) """ Функция добавление лабы """ def lab_add_view(request): weightKt1 = 100 weightKt2 = 100 weightKt3 = 100 labsKt1 = Laboratory.objects.filter(kt=1) labsKt2 = Laboratory.objects.filter(kt=2) labsKt3 = Laboratory.objects.filter(kt=3) for labKt1 in labsKt1: weightKt1 -= labKt1.weight for labKt2 in labsKt2: weightKt2 -= labKt2.weight for labKt3 in labsKt3: weightKt3 -= labKt3.weight if request.method == 'POST': form = LabForm(request.POST) if form.is_valid(): form.save() students = Student.objects.filter(group_id=request.POST['group_id']) lab = Laboratory.objects.filter(name=request.POST['name']) for student in students: if not Stats.objects.filter(lab=lab[0], student=student): stats = Stats(student=student, lab=lab[0], status=False) stats.save() return redirect(request.GET['next']) else: form = LabForm() context = { 'form': form, 'weightKt1': weightKt1, 'weightKt2': weightKt2, 'weightKt3': weightKt3 } return render(request, template_name='botbi20i1/labCreate_page.html', context=context) def lab_pk(pk): #/lab/52/?next=/group/10/ lab_pk = '' change_pk = pk[5:-7] for i in change_pk: if i.isdigit(): lab_pk += i return lab_pk """ Функция добавления файла с заданием студента """ def FileAddView(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): pk = request.GET['next'] print(request.GET) print(type(pk[5])) lab_id = lab_pk(request.GET['next']) print(lab_id) student = Student.objects.filter(user=request.user) lab = Laboratory.objects.filter(pk=lab_id) file = form.save(commit=False) file.lab = lab[0] file.student = student[0] file.save() print(lab[0]) return redirect(request.GET['next']) else: form = FileForm() context = { 'form': form } return render(request, template_name='botbi20i1/add_file.html', context=context) """ Функция изменения файла студентом """ def FileChangeView(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): lab_id = lab_pk(request.GET['next']) student = Student.objects.filter(user=request.user) lab = Laboratory.objects.filter(pk=lab_id) File.objects.get(student=student[0], lab=lab[0]).delete() file = form.save(commit=False) file.lab = lab[0] file.student = student[0] file.save() return redirect(request.GET['next']) else: form = FileForm() context = { 'form': form } return render(request, template_name='botbi20i1/change_file.html', context=context) """ Функция удаления файла студентом """ def FileDeleteView(request): lab_id = lab_pk(request.GET['next']) student = Student.objects.filter(user=request.user) lab = Laboratory.objects.filter(pk=lab_id) File.objects.get(student=student[0], lab=lab[0]).delete() return redirect(request.GET['next'])
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,578
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0055_remove_stats_group_id.py
# Generated by Django 3.1.2 on 2021-02-11 18:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0054_stats_group_id'), ] operations = [ migrations.RemoveField( model_name='stats', name='group_id', ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,579
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0051_stats_group.py
# Generated by Django 3.1.2 on 2021-02-09 18:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0050_auto_20210205_0258'), ] operations = [ migrations.AddField( model_name='stats', name='group', field=models.ForeignKey(default=10, on_delete=django.db.models.deletion.CASCADE, to='botbi20i1.group'), preserve_default=False, ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,580
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0064_auto_20210317_1755.py
# Generated by Django 3.1.7 on 2021-03-17 17:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0063_auto_20210317_1634'), ] operations = [ migrations.AddField( model_name='group', name='teacher', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='botbi20i1.teacher'), ), migrations.AlterField( model_name='educationcontrol', name='group', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='botbi20i1.group', verbose_name='Группа'), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,581
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/forms.py
from django.contrib.auth.models import User from django.forms import ModelForm, HiddenInput, ModelChoiceField from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm from .models import Laboratory, Student, File, Teacher class LabForm(ModelForm): class Meta: model = Laboratory fields = '__all__' class FileForm(ModelForm): class Meta: model = File fields = {'file', 'lab', 'student'} class AuthUserForm(AuthenticationForm, ModelForm): class Meta: model = User fields = {'password', 'username'} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control' class ChangePasswordForm(PasswordChangeForm, ModelForm): class Meta: model = User fields = {'old_password', 'new_password1', 'new_password2'} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control' class RegisterUserForm(ModelForm): class Meta: model = User fields = {'username', 'password'} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control' def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data['password']) if commit: user.save() return user class EditTeacherInformationForm(ModelForm): class Meta: model = Teacher fields = {'email', 'phone', 'additional_information', }
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,582
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0020_auto_20210102_2055.py
# Generated by Django 3.1.2 on 2021-01-02 14:55 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0019_auto_20201228_2103'), ] operations = [ migrations.DeleteModel( name='Rating', ), migrations.AddField( model_name='laboratory', name='date_added', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,583
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0039_auto_20210116_1622.py
# Generated by Django 3.1.2 on 2021-01-16 10:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0038_auto_20210116_1617'), ] operations = [ migrations.RenameModel( old_name='Files', new_name='File', ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,584
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0002_auto_20201121_0220.py
# Generated by Django 3.1.2 on 2020-11-20 20:20 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0001_initial'), ] operations = [ migrations.AddField( model_name='student', name='rating_1KT', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(100)]), ), migrations.AddField( model_name='student', name='rating_2KT', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(100)]), ), migrations.AddField( model_name='student', name='rating_3KT', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(100)]), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,585
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0063_auto_20210317_1634.py
# Generated by Django 3.1.7 on 2021-03-17 16:34 import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0062_auto_20210317_1621'), ] operations = [ migrations.AddField( model_name='educationcontrol', name='group', field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, to='botbi20i1.group'), preserve_default=False, ), migrations.AlterField( model_name='educationcontrol', name='number', field=models.IntegerField(choices=[(1, 1), (2, 2), (3, 3)], default='1', verbose_name='Номер КТ'), ), migrations.AlterField( model_name='educationcontrol', name='weight', field=models.IntegerField(default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100.0)], verbose_name='Вес КТ (%)'), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,586
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0065_laboratory_comment.py
# Generated by Django 3.1.7 on 2021-05-28 17:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0064_auto_20210317_1755'), ] operations = [ migrations.AddField( model_name='laboratory', name='comment', field=models.TextField(blank=True, default='', verbose_name='Комментарий преподователя'), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,587
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0046_auto_20210205_0152.py
# Generated by Django 3.1.2 on 2021-02-04 19:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0045_auto_20210205_0146'), ] operations = [ migrations.RemoveField( model_name='file', name='lab', ), migrations.AddField( model_name='file', name='lab', field=models.ManyToManyField(to='botbi20i1.Laboratory'), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,588
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0067_remove_student_student_dir.py
# Generated by Django 3.1.7 on 2021-05-28 17:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0066_student_student_dir'), ] operations = [ migrations.RemoveField( model_name='student', name='student_dir', ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,589
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0060_educationcontrol.py
# Generated by Django 3.1.7 on 2021-03-17 16:10 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0059_laboratory_weight'), ] operations = [ migrations.CreateModel( name='EducationControl', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('number', models.IntegerField(choices=[('1', '1'), ('2', '2'), ('3', '3')], default=1)), ('weight', models.IntegerField(default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100.0)])), ], ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,590
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0019_auto_20201228_2103.py
# Generated by Django 3.1.2 on 2020-12-28 15:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0018_auto_20201226_1658'), ] operations = [ migrations.AlterField( model_name='laboratory', name='description', field=models.TextField(default='', verbose_name='Описание'), ), migrations.AlterField( model_name='laboratory', name='kt', field=models.PositiveIntegerField(default=1, verbose_name='КТ'), ), migrations.AlterField( model_name='laboratory', name='name', field=models.CharField(default='', max_length=200, verbose_name='Название'), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,591
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/admin.py
from django.contrib import admin # Register your models here. from .models import Student, Laboratory, Hint, Stats, Group, File, Teacher, EducationControl admin.site.register(Hint) admin.site.register(Student) admin.site.register(Laboratory) admin.site.register(Stats) admin.site.register(Group) admin.site.register(File) admin.site.register(Teacher) admin.site.register(EducationControl)
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,592
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/std_KZ9S39y.py
a = input() b = input() c = input() if b > a: if c > a: print(a, "min") elif c == a: print(a, c, "min") else: print(c, "min") elif b == a: if c > a: print(a, b , "min") elif c == a: print(a, b, c, "min") else: print(c, "min") else: if c > b: print(b, " min") elif c == b: print(b, c, "min") else: print(c, "min")
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,593
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0043_auto_20210204_2116.py
# Generated by Django 3.1.2 on 2021-02-04 15:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0042_teacher'), ] operations = [ migrations.RemoveField( model_name='file', name='student', ), migrations.AddField( model_name='file', name='student', field=models.ManyToManyField(to='botbi20i1.Student'), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,594
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0069_auto_20210528_1755.py
# Generated by Django 3.1.7 on 2021-05-28 17:55 import botbi20i1.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0068_student_student_dir'), ] operations = [ migrations.AddField( model_name='laboratory', name='file_input', field=models.FileField(blank=True, default=None, upload_to=botbi20i1.models.folder_path_fileIn), ), migrations.AddField( model_name='laboratory', name='file_output', field=models.FileField(blank=True, default=None, upload_to=botbi20i1.models.folder_path_fileOut), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,595
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0070_auto_20210530_2127.py
# Generated by Django 3.1.7 on 2021-05-30 21:27 import botbi20i1.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0069_auto_20210528_1755'), ] operations = [ migrations.AlterField( model_name='file', name='file', field=models.FileField(default=None, upload_to=botbi20i1.models.folder_path_students_file), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,596
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0057_auto_20210226_1838.py
# Generated by Django 3.1.6 on 2021-02-26 18:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0056_auto_20210225_2017'), ] operations = [ migrations.AddField( model_name='teacher', name='additional_Information', field=models.CharField(default='', max_length=200), ), migrations.AddField( model_name='teacher', name='email', field=models.CharField(default='', max_length=50), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,597
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0058_auto_20210226_1859.py
# Generated by Django 3.1.6 on 2021-02-26 18:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0057_auto_20210226_1838'), ] operations = [ migrations.RenameField( model_name='teacher', old_name='additional_Information', new_name='additional_information', ), migrations.AddField( model_name='student', name='email', field=models.CharField(default='', max_length=50), ), migrations.AddField( model_name='student', name='patronymic', field=models.CharField(default='', max_length=50), ), migrations.AddField( model_name='student', name='phone', field=models.CharField(default='', max_length=50), ), migrations.AddField( model_name='student', name='second_name', field=models.CharField(default='', max_length=50), ), migrations.AlterField( model_name='student', name='name', field=models.CharField(default='', max_length=50), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,598
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0050_auto_20210205_0258.py
# Generated by Django 3.1.2 on 2021-02-04 20:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0049_auto_20210205_0158'), ] operations = [ migrations.AlterField( model_name='file', name='lab', field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='botbi20i1.laboratory'), ), migrations.AlterField( model_name='file', name='student', field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='botbi20i1.student'), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,599
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/telebotsibadi/files/media/LABA/output/Списки_1.py
footballTeam = ['Neuer', 'Ramos', 'Kroos', 'Messi', 'Ronaldo'] reserve = [] goalkeepers = [] defenders = [] halfbacks = [] forwards = [] for f in footballTeam: print("Вот такую команду я хотел бы видеть в минифутболе,которая состоит из", len(footballTeam), 'игроков:', footballTeam) reserve.append('Ter Stegen') reserve.append('Humels') reserve.append('Coutinho') reserve.append('Lewandowski') reserve.append('Bale') print('В запасе у меня будет тоже', len(reserve), 'игроков.') print('Мои запасные игроки:', reserve) goalkeepers.append(footballTeam[:1]) goalkeepers.append(reserve[:1]) defenders.append(footballTeam[1:2]) defenders.append(reserve[1:2]) halfbacks.append(footballTeam[2:3]) halfbacks.append(reserve[2:3]) forwards.append(footballTeam[3:4]) forwards.append(footballTeam[4:5]) forwards.append(reserve[3:4]) forwards.append(reserve[4:5]) print('Моя заявка на игры:') print('Вратари:', goalkeepers) print('Защитники:', defenders) print('Полузащитники:', halfbacks) print('Нападющие:', forwards) break
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,600
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0013_remove_student_group.py
# Generated by Django 3.1.2 on 2020-12-15 18:23 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0012_student_group_id'), ] operations = [ migrations.RemoveField( model_name='student', name='group', ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,601
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0052_remove_stats_group.py
# Generated by Django 3.1.2 on 2021-02-09 18:55 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0051_stats_group'), ] operations = [ migrations.RemoveField( model_name='stats', name='group', ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,602
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0023_auto_20210106_2132.py
# Generated by Django 3.1.2 on 2021-01-06 15:32 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('botbi20i1', '0022_auto_20210106_2131'), ] operations = [ migrations.AlterField( model_name='student', name='login', field=models.ForeignKey(default='student', max_length=50, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,603
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0007_auto_20201206_1635.py
# Generated by Django 3.1.2 on 2020-12-06 10:35 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0006_auto_20201206_1622'), ] operations = [ migrations.AlterField( model_name='student', name='rating', field=models.FloatField(default=0, validators=[django.core.validators.MaxValueValidator(100)]), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,604
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/telebotsibadi/files/media/Laboratory/labalaba/input/std.py
a = "/lav/57/" b = 57 if str(b) in a: print(b) else: print(a)
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,605
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/models.py
from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from django.urls import reverse def folder_path(instance, filename): return "{0}/{1}".format(instance.personal_number, filename) def folder_path_students_file(instance, filename): return "{0}/{1}".format(instance.student.personal_number, filename) def folder_path_fileIn(instance, filename): return "Laboratory/{0}/input/{1}".format(instance.name, filename) def folder_path_fileOut(instance, filename): return "Laboratory/{0}/output/{1}".format(instance.name, filename) """ Преподователь, информация о нем """ class Teacher(models.Model): second_name = models.CharField(max_length=50, default="") name = models.CharField(max_length=50, default="") patronymic = models.CharField(max_length=50, default="") phone = models.CharField(max_length=50, default="") email = models.CharField(max_length=50, default="") additional_information = models.CharField(max_length=200, default="") user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.second_name + " " + self.name + " " + self.patronymic """ Группы """ class Group(models.Model): name = models.CharField(max_length=20, default="") course = models.CharField(max_length=20, default="") teacher = models.ForeignKey(Teacher, default=1, on_delete=models.CASCADE) def __str__(self): return self.name """ Лаборантоные работы """ class Laboratory(models.Model): name = models.CharField(max_length=200, default="", verbose_name="Название") description = models.TextField(default="", verbose_name="Описание") kt = models.PositiveIntegerField(default=1, verbose_name="КТ") comment = models.TextField(default="", blank=True, verbose_name="Комментарий преподователя") group_id = models.ForeignKey(Group, on_delete=models.CASCADE, default=1) date_added = models.DateTimeField(auto_now_add=True) weight = models.FloatField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100.00)], blank=True, verbose_name="Вес лабы (%)") file_input = models.FileField(upload_to= folder_path_fileIn, default= None, blank=True) file_output = models.FileField(upload_to= folder_path_fileOut, default= None, blank=True) def __str__(self): return self.name """ Студент, вся информация о нем, рейтинги """ class Student(models.Model): group_id = models.ForeignKey(Group, on_delete=models.CASCADE, default=1) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) personal_number = models.CharField(max_length=20, default="") second_name = models.CharField(max_length=50, default="") name = models.CharField(max_length=50, default="") patronymic = models.CharField(max_length=50, default="") phone = models.CharField(max_length=50, default="") email = models.CharField(max_length=50, default="") git_hub = models.CharField(max_length=100, default="") rating_1KT = models.FloatField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100.00)]) rating_2KT = models.FloatField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100.00)]) rating_3KT = models.FloatField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100.00)]) rating = models.FloatField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100.00)], ) labs = models.ManyToManyField(Laboratory, through='Stats') student_dir = models.FileField(upload_to= folder_path, default=None, blank=True) def save(self, *args, **kwargs): self.rating = round(self.rating, 2) self.rating_1KT = round(self.rating_1KT, 2) self.rating_2KT = round(self.rating_2KT, 2) self.rating_3KT = round(self.rating_3KT, 2) super(Student, self).save(*args, **kwargs) def __str__(self): return self.second_name + " " + self.name + " " + self.patronymic """ Файлы, которые студент отправляет на проверку """ class File(models.Model): file = models.FileField(upload_to= folder_path_students_file, default=None) lab = models.ForeignKey(Laboratory, blank=True, on_delete=models.CASCADE) student = models.ForeignKey(Student, blank=True, on_delete=models.CASCADE ) def __str__(self): return self.student.name + " " + self.lab.name + " " + self.file.name """ Подсказки, связаны с лабой """ class Hint(models.Model): text = models.TextField(default="") lab = models.ForeignKey(Laboratory, on_delete=models.CASCADE, null=True) def __str__(self): return self.text """ Контольные точки, можно задать вес и связать с группой """ class EducationControl(models.Model): KT = [ (1, (1)), (2, (2)), (3, (3)), ] number = models.IntegerField(default="1", choices=KT, verbose_name='Номер КТ') weight = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100.00)], verbose_name="Вес КТ (%)") group = models.ForeignKey(Group, on_delete=models.CASCADE, default=1, verbose_name="Группа") def __str__(self): return self.group.name + " KT№ " + str(self.number) """ Статистика, лабараторные привязываются к каждому студенту, имеют статус(true/false) """ class Stats(models.Model): lab = models.ForeignKey(Laboratory, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) status = models.BooleanField(default=False) def __str__(self): return self.lab.name + " " + self.student.name
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,606
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/telebotsibadi/files/media/std.py
def lab_pk(pk): #/lab/52/?next=/group/10/ lab_pk = '' change_pk = pk[5:-7] for i in change_pk: if i.isdigit(): lab_pk += i return lab_pk
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,607
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/telebotsibadi/files/media/LABA/input/0_-_1000.py
n = int(input()) if (n == 1 or n % 10 == 1) and n != 11 and n != 111: print(n, " программист") elif 10 <= n <= 20 or 10 <= n % 100 <= 20 or 5 <= n <= 9 or 5 <= n % 10 <= 9 or n == 0 or n % 10 == 0: print(n, " программистов") elif 2 <= n <= 4 or 32 <= n <= 34 or 2 <= n % 100 <= 4 or 2 <= n % 10 <= 4: print(n, " программиста")
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,608
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0011_auto_20201206_1718.py
# Generated by Django 3.1.2 on 2020-12-06 11:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0010_group'), ] operations = [ migrations.RenameField( model_name='group', old_name='groups', new_name='course', ), migrations.AddField( model_name='group', name='name', field=models.CharField(default='', max_length=20), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,609
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0068_student_student_dir.py
# Generated by Django 3.1.7 on 2021-05-28 17:54 import botbi20i1.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0067_remove_student_student_dir'), ] operations = [ migrations.AddField( model_name='student', name='student_dir', field=models.FileField(blank=True, default=None, upload_to=botbi20i1.models.folder_path), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,610
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0017_auto_20201226_0327.py
# Generated by Django 3.1.2 on 2020-12-25 21:27 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0016_auto_20201226_0325'), ] operations = [ migrations.AlterField( model_name='student', name='group_id', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='botbi20i1.group'), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,611
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0012_student_group_id.py
# Generated by Django 3.1.2 on 2020-12-08 15:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0011_auto_20201206_1718'), ] operations = [ migrations.AddField( model_name='student', name='group_id', field=models.ForeignKey(default=4, on_delete=django.db.models.deletion.CASCADE, to='botbi20i1.group'), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,612
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0026_remove_student_login.py
# Generated by Django 3.1.2 on 2021-01-06 15:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0025_auto_20210106_2138'), ] operations = [ migrations.RemoveField( model_name='student', name='login', ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,613
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0059_laboratory_weight.py
# Generated by Django 3.1.7 on 2021-03-15 17:07 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0058_auto_20210226_1859'), ] operations = [ migrations.AddField( model_name='laboratory', name='weight', field=models.FloatField(blank=True, default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100.0)], verbose_name='Вес лабы (%)'), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,614
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/telebotsibadi/files/media/Laboratory/labalaba/output/дз1.py
x = int(input("Введите количество яблок: ")) y = int(input("Введите количество человек: ")) print(x // y, "Столько яблок можно разделить поровну межу ", y, "людьми.") print(x % y, " Столько яблок осталось.")
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,615
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0056_auto_20210225_2017.py
# Generated by Django 3.1.6 on 2021-02-25 20:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0055_remove_stats_group_id'), ] operations = [ migrations.AddField( model_name='teacher', name='patronymic', field=models.CharField(default='', max_length=50), ), migrations.AddField( model_name='teacher', name='phone', field=models.CharField(default='', max_length=50), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,616
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0018_auto_20201226_1658.py
# Generated by Django 3.1.2 on 2020-12-26 10:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0017_auto_20201226_0327'), ] operations = [ migrations.RemoveField( model_name='laboratory', name='code', ), migrations.AlterField( model_name='student', name='group_id', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='botbi20i1.group'), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,617
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/urls.py
from django.urls import path from django.conf import settings from django.conf.urls.static import static from .views import index, facePage, group, labsPage, studentPage, FileChangeView, FileDeleteView from .views import update_changes,lab_add_view, LoginUserView, RegisterUserView, LogoutView, userPage, ChangePasswordView, \ FileAddView, view_info urlpatterns = [ path('', facePage.as_view(), name='face_page'), path('face_page', facePage.as_view(), name='face_page'), path(r'json_response/<int:index_id>/', index, name='index_page'), path(r'group/<int:group_id>/', group, name='group_page'), path(r'lab/<int:id>/', labsPage, name='labs_page'), path(r'student/<int:id>/', studentPage, name='student_page'), path(r'api/v1/update_stats_status', update_changes, name='update_api'), path(r'addlab', lab_add_view, name='addlab_page'), path(r'login', LoginUserView.as_view(), name='login_page'), path(r'user', userPage.as_view(), name='user_page'), path(r'registration', RegisterUserView.as_view(), name='register_page'), path(r'changepassword', ChangePasswordView, name='changepassword_page'), path(r'addfile', FileAddView, name='add_file'), path(r'changefile', FileChangeView, name='change_file'), path(r'delete_file', FileDeleteView, name='delete_file'), path(r'info', view_info, name='info'), path(r'logout', LogoutView.as_view(next_page = 'face_page'), name='logout') ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,618
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0001_initial.py
# Generated by Django 3.1.2 on 2020-11-20 18:37 import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Laboratory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.TextField(default='')), ('name', models.CharField(default='', max_length=200)), ('kt', models.PositiveIntegerField(default=1)), ], ), migrations.CreateModel( name='Rating', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='Контрольная точка №1', max_length=30)), ('rating', models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(100)])), ], ), migrations.CreateModel( name='Stats', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('status', models.BooleanField(default=False)), ('lab', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='botbi20i1.laboratory')), ], ), migrations.CreateModel( name='Student', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('group', models.CharField(default='', max_length=20)), ('name', models.CharField(default='', max_length=60)), ('rating', models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(100)])), ('labs', models.ManyToManyField(through='botbi20i1.Stats', to='botbi20i1.Laboratory')), ], ), migrations.AddField( model_name='stats', name='student', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='botbi20i1.student'), ), migrations.CreateModel( name='Hint', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.TextField(default='')), ('lab', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='botbi20i1.laboratory')), ], ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,619
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/apps.py
from django.apps import AppConfig class Botbi20I1Config(AppConfig): name = 'botbi20i1'
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,620
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0014_auto_20201220_0825.py
# Generated by Django 3.1.2 on 2020-12-20 02:25 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0013_remove_student_group'), ] operations = [ migrations.AlterField( model_name='student', name='rating', field=models.FloatField(default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)]), ), migrations.AlterField( model_name='student', name='rating_1KT', field=models.FloatField(default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100.0)]), ), migrations.AlterField( model_name='student', name='rating_2KT', field=models.FloatField(default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100.0)]), ), migrations.AlterField( model_name='student', name='rating_3KT', field=models.FloatField(default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)]), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,621
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0005_auto_20201206_1611.py
# Generated by Django 3.1.2 on 2020-12-06 10:11 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0004_student_personal_number'), ] operations = [ migrations.AlterField( model_name='student', name='rating', field=models.FloatField(default=0, validators=[django.core.validators.MaxValueValidator(100)]), ), migrations.AlterField( model_name='student', name='rating_1KT', field=models.FloatField(default=0, validators=[django.core.validators.MaxValueValidator(100)]), ), migrations.AlterField( model_name='student', name='rating_2KT', field=models.FloatField(default=0, validators=[django.core.validators.MaxValueValidator(100)]), ), migrations.AlterField( model_name='student', name='rating_3KT', field=models.FloatField(default=0, validators=[django.core.validators.MaxValueValidator(100)]), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,622
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0015_laboratory_code.py
# Generated by Django 3.1.2 on 2020-12-25 20:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0014_auto_20201220_0825'), ] operations = [ migrations.AddField( model_name='laboratory', name='code', field=models.FileField(default='', upload_to=''), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,623
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0008_auto_20201206_1641.py
# Generated by Django 3.1.2 on 2020-12-06 10:41 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0007_auto_20201206_1635'), ] operations = [ migrations.AlterField( model_name='student', name='rating', field=models.FloatField(default=0, validators=[django.core.validators.MaxValueValidator(100, 0)]), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,624
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0029_remove_student_user.py
# Generated by Django 3.1.2 on 2021-01-06 15:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0028_auto_20210106_2153'), ] operations = [ migrations.RemoveField( model_name='student', name='user', ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,253,625
vanya22551/sibadiservice
refs/heads/master
/telebotsibadi/botbi20i1/migrations/0062_auto_20210317_1621.py
# Generated by Django 3.1.7 on 2021-03-17 16:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('botbi20i1', '0061_auto_20210317_1617'), ] operations = [ migrations.AlterField( model_name='educationcontrol', name='number', field=models.IntegerField(choices=[('1', 1), ('2', 2), ('3', 3)], default='1'), ), ]
{"/hakaton/hakaton/boTtelegramm/views.py": ["/hakaton/hakaton/boTtelegramm/models.py", "/hakaton/hakaton/boTtelegramm/forms.py"], "/hakaton/hakaton/boTtelegramm/urls.py": ["/hakaton/hakaton/boTtelegramm/views.py"], "/hakaton/hakaton/boTtelegramm/admin.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/hakaton/hakaton/boTtelegramm/forms.py": ["/hakaton/hakaton/boTtelegramm/models.py"], "/telebotsibadi/botbi20i1/views.py": ["/telebotsibadi/botbi20i1/models.py", "/telebotsibadi/botbi20i1/forms.py"], "/telebotsibadi/botbi20i1/forms.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/admin.py": ["/telebotsibadi/botbi20i1/models.py"], "/telebotsibadi/botbi20i1/urls.py": ["/telebotsibadi/botbi20i1/views.py"]}
31,322,430
UCLComputerScience/COMP0016_2020_21_Team35
refs/heads/main
/voiceflow_to_json/voiceflow_to_json.py
import requests import json import copy class Simplified_Json: def __init__(self, diagram_json, intents=None): self.diagram_json = diagram_json self.intents = intents def get_nodes(self): nodes = [] for node in self.diagram_json["nodes"]: nodes.append(node) return nodes def get_step(self, node): step = "" node_data = self.diagram_json["nodes"][node]["data"] i = 0 if("steps" in node_data): i += 1 if(i > 1): raise Exception("There are more than one step. Not allowed for IVR") for step in node_data["steps"]: step = step return step def get_dialogs(self, node): dialogs = [] node_data = self.diagram_json["nodes"][node]["data"] if("dialogs" in node_data): for dialog in node_data["dialogs"]: if("content" in dialog): if dialog["content"]: dialogs.append(dialog["content"]) return dialogs def get_target_nodes(self, node): target_nodes = set() node_data = self.diagram_json["nodes"][node]["data"] if("ports" in node_data): for port in node_data["ports"]: if("target" in port): child = port["target"] if(child == None): target_nodes.add(child) elif ("steps" in self.diagram_json["nodes"][child]["data"]): target_nodes.add(self.get_step(child)) else: target_nodes.add(child) return target_nodes def get_choices(self, node): node = self.get_step(node) node_data = self.diagram_json["nodes"][node]["data"] choice_nodes = [] yes_choices = ["AMAZON.YesIntent"] no_choices = ["AMAZON.NoIntent"] if not self.intents == None: for key in self.intents: if "yes" in self.intents[key]: yes_choices.append(key) elif "no" in self.intents[key]: no_choices.append(key) if("choices" in node_data): if("ports" in node_data): for port in node_data["ports"]: if port["target"] != None: target = port["target"] if ("steps" in self.diagram_json["nodes"][target]["data"]): choice_nodes.append(self.get_step(port["target"])) else: choice_nodes.append(port["target"]) if(len(choice_nodes) != 2): raise Exception("Only deal with choice commands with 2 options") if(node_data["choices"][0]["intent"] in no_choices): choice_nodes[0], choice_nodes[1] = choice_nodes[1], choice_nodes[0] if(node_data["choices"][1]["intent"] not in yes_choices): print(node_data["choices"][1]["intent"]) raise Exception("Must have Yes and No options only for a choice") elif(node_data["choices"][0]["intent"] not in yes_choices): raise Exception("Must have Yes and No options only for a choice") return choice_nodes def is_interaction(self, node): if(self.diagram_json["nodes"][node]["type"] == "interaction"): return True else: return False def reorder_nodes(self, simplified_json): temp_map = copy.deepcopy(simplified_json) nodes = simplified_json["nodes"] for node in simplified_json["nodes"]: temp_node = nodes[node] if("children" in temp_node): try: del temp_map["nodes"][temp_node["children"][0]] except: pass elif("choices" in temp_node): for choice in temp_node["choices"]: try: del temp_map["nodes"][choice] except: pass first_node = next(iter(temp_map["nodes"])) new_json = {"nodes": {}} new_json["nodes"][first_node] = nodes[first_node] for node in nodes: if node == first_node: continue else: new_json["nodes"][node] = nodes[node] return new_json # curNode = first_node # lastNode = curNode # choice_nodes = [] # while(nodes): # if(curNode in nodes and "children" in nodes[curNode] and nodes[curNode]["children"][0] != None): # curNode = nodes[curNode]["children"][0] # elif(curNode in nodes and "choices" in nodes[curNode]): # choice_nodes.append(nodes[curNode]["choices"][1]) # curNode = nodes[curNode]["choices"][0] # elif choice_nodes: # curNode = choice_nodes[-1] # del choice_nodes[-1] # # if(curNode in nodes): # print(nodes) # print(curNode) # print(lastNode) # new_json["nodes"][curNode] = nodes[curNode] # if(lastNode in nodes): # del nodes[lastNode] # lastNode = curNode # print(new_json) # return new_json # Issue if the output from a choice command is connected to an individual text on voiceflow instead of to the whole box (should fix this). # Likely fix is to swap so that the nodes in use in the simplified JSON will be the actual nodes containing dialog and the actual choice node. # This will require some refactoring. def simplify_json(self): nodes = self.get_nodes() node_dict = {} node_dict["nodes"] = {} for node in nodes: node_step = self.get_step(node) choices = [] if(node_step): choices = self.get_choices(node) if(not self.get_dialogs(node)): if(not node_step and not choices): continue else: continue dialogs = [] children = set() if(not self.is_interaction(node_step)): dialogs.extend(self.get_dialogs(node_step)) children = children | self.get_target_nodes(node_step) if(not dialogs and not choices): continue node_dict["nodes"][node_step] = {} if(dialogs): node_dict["nodes"][node_step]["dialogs"] = dialogs if(children): node_dict["nodes"][node_step]["children"] = list(children) if(choices): node_dict["nodes"][node_step]["choices"] = choices reordered_dict = self.reorder_nodes(node_dict) return reordered_dict class Get_Voiceflow_Information: def __init__(self, email, password): self.email = email self.password = password def get_auth_header(self): AUTH_URL = "https://api.voiceflow.com/session" payload = {"user":{"email":self.email,"password":self.password}} headers = {"Content-type": "application/json"} try: auth = requests.put(AUTH_URL, data=json.dumps(payload), headers=headers) token = auth.json()["token"] header = {"Authorization": token} except Exception: header = "None" return header def get_workspaces(self, headers): workspaces = [] WORKSPACE_URL = "https://api.voiceflow.com/workspaces" workspace_request = requests.get(WORKSPACE_URL, headers=headers).json() for workspace in workspace_request: workspaces.append({"name": workspace["name"], "id": workspace["team_id"]}) return workspaces def get_workspace_names(self, workspaces): workspace_names = [] for workspace in workspaces: workspace_names.append(workspace["name"]) return workspace_names def get_projects(self, headers, workspace_id): projects = [] PROJECT_URL = "https://api.voiceflow.com/v2/workspaces/" + workspace_id + "/projects" project_request = requests.get(PROJECT_URL, headers=headers).json() for project in project_request: int_id = int(project["devVersion"], 16) + 1 hex_id = format(int_id, "x") project_id = str(hex_id) projects.append({"name": project["name"], "id": project_id}) return projects def get_project_names(self, projects): project_names = [] for project in projects: project_names.append(project["name"]) return project_names def get_workspace_id(self, workspace_name, workspaces): for workspace in workspaces: if workspace["name"] == workspace_name: return workspace["id"] class GetVoiceflowSettings: def __init__(self, simplified_json): self.simplified_json = simplified_json def get_redirect_texts(self): redirect_texts = {} if self.simplified_json is None: return -1 for node in self.simplified_json["nodes"]: if (not "children" in self.simplified_json["nodes"][node] or self.simplified_json["nodes"][node]["children"][0] == None) and not "choices" in self.simplified_json["nodes"][node]: if "dialogs" in self.simplified_json["nodes"][node]: redirect_text = "" for dialog in self.simplified_json["nodes"][node]["dialogs"]: redirect_text += dialog redirect_texts[node] = redirect_text return redirect_texts def get_ivr_texts(self): ivr_texts = {} for node in self.simplified_json["nodes"]: if not "choices" in self.simplified_json["nodes"][node]: if "dialogs" in self.simplified_json["nodes"][node]: ivr_text = "" for dialog in self.simplified_json["nodes"][node]["dialogs"]: ivr_text += dialog ivr_texts[node] = ivr_text return ivr_texts class Voiceflow_To_Json: def __init__(self, workspace_name, project_name, headers): self.workspace_name = workspace_name self.project_name = project_name self.headers = headers def get_workspace_id(self): WORKSPACE_URL = "https://api.voiceflow.com/workspaces" workspaces = requests.get(WORKSPACE_URL, headers=self.headers).json() for workspace in workspaces: if workspace["name"] == self.workspace_name: workspace_id = workspace["team_id"] return workspace_id def get_intents(self): project_id = self.get_project_id() hex_id = hex(int(project_id, 16) - 1)[2:] project_id = str(hex_id) VERSIONS_URL = "https://api.voiceflow.com/v2/versions/" + project_id versions = requests.get(VERSIONS_URL, headers=self.headers).json() intents = {} for key in versions["platformData"]["intents"]: intents[versions["intents"][key]["key"]] = versions["intents"][key]["name"] return intents def get_project_id(self): workspace_id = self.get_workspace_id() PROJECT_URL = "https://api.voiceflow.com/v2/workspaces/" + workspace_id + "/projects" projects = requests.get(PROJECT_URL, headers=self.headers).json() for project in projects: if project["name"] == self.project_name: int_id = int(project["devVersion"], 16) + 1 hex_id = format(int_id, "x") project_id = str(hex_id) return project_id def get_diagram_json(self): project_id = self.get_project_id() DIAGRAM_URL = "https://api.voiceflow.com/v2/diagrams/" + project_id diagram_json = requests.get(DIAGRAM_URL, headers=self.headers).json() return diagram_json def simplified_json(self): diagram_json = self.get_diagram_json() intents = self.get_intents() json_object = Simplified_Json(diagram_json, intents) simplified_json = json_object.simplify_json() return simplified_json class VoiceflowFileToJson(): def __init__(self, filepath): self.filepath = filepath def assign_json_dict(self): with open(self.filepath) as file: voiceflow_json = json.load(file) return voiceflow_json def decode_root_diagram(self, voiceflow_json): root_diagram = voiceflow_json["version"]["rootDiagramID"] diagram_json = voiceflow_json["diagrams"][root_diagram] return diagram_json def get_intents(self, voiceflow_json): intents = {} json_intents = voiceflow_json["version"]["platformData"]["intents"] for key in json_intents: intents[key["key"]] = key["name"] return intents def simplified_json(self): voiceflow_json = self.assign_json_dict() diagram_json = self.decode_root_diagram(voiceflow_json) intents = self.get_intents(voiceflow_json) json_object = Simplified_Json(diagram_json, intents) simplified_json = json_object.simplify_json() return simplified_json # email = input("Email: ") # password = getpass.getpass(prompt="Password: ") # workspace = input("Workspace: ") # project = input("Project: ") # test = Voiceflow_To_Json(email, password, workspace, project) # print(test.get_auth_header()) #test1 = test.simplified_json(test.get_auth_header()) # with open('/home/max/Documents/GP_IVR/voiceflow.json', 'w') as fp: # json.dump(test1, fp)
{"/main_application/ui_modules/home_page.py": ["/main_application/constants/image_filepath_constants.py"], "/main_application/settings_modifications/settings_to_pjsip.py": ["/main_application/connect_to_asterisk/asterisk_manager.py"], "/main_application/json_to_dialplan/json_to_dialplan.py": ["/main_application/json_to_dialplan/generate_voice_files.py", "/main_application/connect_to_asterisk/asterisk_manager.py", "/main_application/constants/asterisk_filepath_constants.py"], "/main_application/ui_modules/redirect_settings_page.py": ["/main_application/voiceflow_to_json/json_decoder.py", "/main_application/settings_modifications/settings_to_dialplan.py", "/main_application/constants/asterisk_filepath_constants.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/ui_modules/UI.py": ["/main_application/ui_modules/add_voice_files_page.py", "/main_application/ui_modules/choose_voiceflow_file_page.py", "/main_application/ui_modules/home_page.py", "/main_application/ui_modules/ivr_generator_page.py", "/main_application/ui_modules/ivr_server_status_page.py", "/main_application/ui_modules/login_page.py", "/main_application/ui_modules/project_page.py", "/main_application/ui_modules/pstn_settings_page.py", "/main_application/ui_modules/redirect_settings_page.py", "/main_application/ui_modules/statistics_page.py"], "/tests/test_main_application/unit_tests/test_voiceflow_to_json.py": ["/main_application/voiceflow_to_json/voiceflow_to_json.py", "/tests/test_main_application/unit_tests/voiceflow_constants.py"], "/tests/test_main_application/unit_tests/test_ui/test_login_page.py": ["/main_application/ui_modules/UI.py"], "/tests/test_main_application/unit_tests/test_ivr_server.py": ["/main_application/constants/docker_constants.py", "/main_application/settings_modifications/ivr_server.py"], "/main_application/ui_modules/add_voice_files_page.py": ["/main_application/voiceflow_to_json/json_decoder.py", "/main_application/settings_modifications/modify_voice_files.py", "/main_application/constants/asterisk_filepath_constants.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/ui_modules/ivr_generator_page.py": ["/main_application/constants/image_filepath_constants.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/ui_modules/statistics_page.py": ["/main_application/statistics/extract_data.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/ui_modules/pstn_settings_page.py": ["/main_application/settings_modifications/settings_to_pjsip.py", "/main_application/constants/asterisk_filepath_constants.py", "/main_application/ui_modules/shared_buttons.py"], "/tests/test_main_application/integration_tests/test_voiceflow_to_json.py": ["/main_application/voiceflow_to_json/voiceflow_to_json.py", "/tests/test_main_application/integration_tests/voiceflow_constants.py"], "/main_application/ui_modules/project_page.py": ["/main_application/voiceflow_to_json/voiceflow_to_json.py", "/main_application/json_to_dialplan/json_to_dialplan.py", "/main_application/constants/asterisk_filepath_constants.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/statistics/extract_data.py": ["/main_application/constants/asterisk_filepath_constants.py"], "/tests/test_main_application/unit_tests/test_ui/test_home_page.py": ["/main_application/ui_modules/UI.py"], "/main_application/ui_modules/login_page.py": ["/main_application/voiceflow_to_json/voiceflow_to_json.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/ui_modules/choose_voiceflow_file_page.py": ["/main_application/voiceflow_to_json/voiceflow_to_json.py", "/main_application/json_to_dialplan/json_to_dialplan.py", "/main_application/constants/asterisk_filepath_constants.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/settings_modifications/ivr_server.py": ["/main_application/constants/docker_constants.py", "/main_application/constants/test_docker_constants.py"], "/main_application/ui_modules/ivr_server_status_page.py": ["/main_application/constants/image_filepath_constants.py", "/main_application/settings_modifications/ivr_server.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/settings_modifications/settings_to_dialplan.py": ["/main_application/connect_to_asterisk/asterisk_manager.py"], "/main_application/voiceflow_to_json/voiceflow_to_json.py": ["/main_application/voiceflow_to_json/json_decoder.py"], "/main_application/ui_modules/shared_buttons.py": ["/main_application/constants/image_filepath_constants.py"]}
31,322,431
UCLComputerScience/COMP0016_2020_21_Team35
refs/heads/main
/voiceflow_to_json/UI.py
import sys import os from PyQt5.QtWidgets import QDialog, QGroupBox, QMainWindow, QFormLayout, QLabel, QVBoxLayout, QHBoxLayout, QPushButton, QProxyStyle, QStyle from PyQt5.QtWidgets import QComboBox, QWidget, QApplication, QAction, qApp, QButtonGroup, QFileDialog, QMessageBox, QLineEdit, QSizePolicy, QScrollArea from PyQt5.QtCore import QSettings, Qt, QSize, QRect, QPoint from PyQt5.QtGui import QIcon, QFont, QPixmap from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar import numpy as np import matplotlib.pyplot as plt from pathlib import Path import subprocess from voiceflow_to_json import Get_Voiceflow_Information, Voiceflow_To_Json, VoiceflowFileToJson, GetVoiceflowSettings from json_to_dialplan.json_to_dialplan import Dialplan from settings_to_pjsip import SettingsToPjsip from settings_to_dialplan import SettingsToDialplan from extract_data import return_daily_data, return_weekly_data from modify_voice_files import ModifyVoiceFiles subprocess.run("sudo apt-get install libsndfile1-dev".split()) if getattr(sys, 'frozen', False): application_path = os.path.dirname(sys.executable) else: application_path = os.path.dirname(__file__) class BackButton: def create_back_button(self): back_button = QPushButton("Back") back_icon = QIcon(os.path.join(application_path, "voiceflow_to_json/ui_assets/back_icon.png")) back_button.setIcon(back_icon) back_button.setIconSize(QSize(16, 16)) back_button.setToolTip("Go To Previous Page") return back_button def create_back_layout(self, back_button): back_layout = QHBoxLayout() back_layout.addWidget(back_button) back_layout.addWidget(QLabel()) back_layout.addWidget(QLabel()) back_layout.addWidget(QLabel()) return back_layout class ProjectWindow(QDialog): def __init__(self, voiceflow_api, headers): super().__init__() self.voiceflow_api = voiceflow_api self.headers = headers self.init_ui() def init_ui(self): self.layout = QVBoxLayout() self.form_layout = QFormLayout() heading_font = QFont('Arial', 12) heading_font.setBold(True) heading = QLabel("Choose Workspace and Project:") heading.setFont(heading_font) self.layout.addWidget(QLabel()) self.layout.addWidget(heading) page_info = QLabel("You can choose a Voiceflow project within a workspace to be used to generate your IVR") self.layout.addWidget(page_info) self.layout.addWidget(QLabel()) self.button_group = QGroupBox() self.layout.addWidget(self.button_group) self.v_box = QVBoxLayout() self.button_group.setLayout(self.v_box) self.workspace_combo_box = QComboBox(self) self.workspace_combo_box.setToolTip("Choose the workspace where your project is located on Voiceflow") self.projects_combo_box = QComboBox(self) self.projects_combo_box.setToolTip("Choose the Voiceflow project to be transferred into an IVR") self.set_projects() self.set_workspaces() self.form_layout.addRow('', QLabel()) self.form_layout.addRow('Workspace:', self.workspace_combo_box) self.form_layout.addRow('', QLabel()) self.form_layout.addRow('Projects:', self.projects_combo_box) grow_label = QLabel() self.form_layout.addRow('', grow_label) grow_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.v_box.addLayout(self.form_layout) self.workspace_combo_box.addItem("Select") self.workspace_combo_box.addItems(self.workspace_names) self.create_ivr_button_layout = QHBoxLayout() self.create_ivr_button = QPushButton('Get Config', self) self.create_ivr_button.setToolTip("Replace current IVR with new one, generated by the Voiceflow project") back_button_creator = BackButton() self.back_button = back_button_creator.create_back_button() self.create_ivr_button_layout.addWidget(self.back_button) self.create_ivr_button_layout.addWidget(self.create_ivr_button) self.settings = QSettings("simplified_voiceflow", "GP_IVR_Settings") self.v_box.addLayout(self.create_ivr_button_layout) self.setLayout(self.layout) def set_projects(self): self.projects = [] self.project_names = [] self.project_name = "" def set_workspaces(self): self.workspaces = self.voiceflow_api.get_workspaces(self.headers) self.workspace_name = "" self.workspace_names = self.voiceflow_api.get_workspace_names(self.workspaces) def create_ivr(self): if not self.project_name: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error\n\nYou have not chosen a project") msg.setWindowTitle("Error") msg.exec_() return voiceflow_json = Voiceflow_To_Json(self.workspace_name, self.project_name, self.headers) simplified_json = voiceflow_json.simplified_json() self.settings.setValue("simplified json", simplified_json) create_ivr = Dialplan("asterisk_docker/conf/asterisk-build/extensions.conf", simplified_json) create_ivr.create_config() def on_project_changed(self, value): self.project_name = value def on_workspace_changed(self, value): self.workspace_name = value workspace_id = self.voiceflow_api.get_workspace_id(value, self.workspaces) self.projects = self.voiceflow_api.get_projects(self.headers, workspace_id) project_names = self.voiceflow_api.get_project_names(self.projects) self.projects_combo_box.clear() self.projects_combo_box.addItem("Select") self.projects_combo_box.addItems(project_names) class VfFileEdit(QLineEdit): def __init__(self, parent): super(VfFileEdit, self).__init__(parent) self.setDragEnabled(True) def dragEnterEvent(self, event): data = event.mimeData() urls = data.urls() if urls and urls[0].scheme() == 'file': event.acceptProposedAction() def dragMoveEvent(self, event): data = event.mimeData() urls = data.urls() if urls and urls[0].scheme() == 'file': event.acceptProposedAction() def dropEvent(self, event): data = event.mimeData() urls = data.urls() if urls and urls[0].scheme() == 'file': filepath = str(urls[0].path()) # Only accept voiceflow files if filepath[-3:].lower() == ".vf": self.setText(filepath) else: dialog = QMessageBox() dialog.setWindowTitle("Error: Invalid File") dialog.setText("Only .vf files are accepted") dialog.setIcon(QMessageBox.Warning) dialog.exec_() class WavFileEdit(QLineEdit): def __init__(self, parent): super(WavFileEdit, self).__init__(parent) self.setDragEnabled(True) def dragEnterEvent(self, event): data = event.mimeData() urls = data.urls() if urls and urls[0].scheme() == 'file': event.acceptProposedAction() def dragMoveEvent(self, event): data = event.mimeData() urls = data.urls() if urls and urls[0].scheme() == 'file': event.acceptProposedAction() def dropEvent(self, event): data = event.mimeData() urls = data.urls() if urls and urls[0].scheme() == 'file': filepath = str(urls[0].path()) # Only accept voiceflow files if filepath[-4:].lower() == ".wav": self.setText(filepath) else: dialog = QMessageBox() dialog.setWindowTitle("Error: Invalid File") dialog.setText("Only .wav files are accepted") dialog.setIcon(QMessageBox.Warning) dialog.exec_() class ChooseVoiceflowFileWidget(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.layout = QVBoxLayout() self.settings = QSettings("simplified_voiceflow", "GP_IVR_Settings") heading_font = QFont('Arial', 12) heading_font.setBold(True) rule_font = QFont("Arial", 10) rule_font.setItalic(True) heading = QLabel("Add Voiceflow File:") heading.setFont(heading_font) page_info = QLabel("Upload a Voiceflow file to be transformed into an IVR.") file_type_rule = QLabel("*File Type Must be .vf") self.layout.addWidget(QLabel()) self.layout.addWidget(heading) self.layout.addWidget(page_info) self.layout.addWidget(file_type_rule) self.layout.addWidget(QLabel()) self.button_group = QGroupBox("Drag and Drop File:") self.layout.addWidget(self.button_group) self.v_box = QVBoxLayout() self.button_group.setLayout(self.v_box) self.file_edit = VfFileEdit(self) self.v_box.addWidget(self.file_edit) grow_label = QLabel() self.v_box.addWidget(grow_label) grow_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.file_edit.setToolTip("Add a .vf file - use either 'Browse' or drag and drop") self.button_layout = QHBoxLayout() self.create_ivr_button = QPushButton("Create IVR", self) self.browse_button = QPushButton("Browse", self) self.browse_button.setToolTip("Browse file manager for .vf file") self.create_ivr_button.setToolTip("Generate an IVR from Voiceflow file and replace your current IVR") back_button_creator = BackButton() self.back_button = back_button_creator.create_back_button() self.button_layout.addWidget(self.back_button) self.button_layout.addWidget(self.browse_button) self.button_layout.addWidget(self.create_ivr_button) self.v_box.addLayout(self.button_layout) self.layout.addLayout(self.v_box) self.setLayout(self.layout) def get_files(self): filepath = QFileDialog.getOpenFileName(self, 'Single File', "~", '*.vf') self.file_edit.setText(filepath[0]) def create_ivr(self): filepath = Path(self.file_edit.text()) if not filepath.is_file(): msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error\n\nThe Path Specified is not a File") msg.setWindowTitle("Error") msg.exec_() return voiceflow_json = VoiceflowFileToJson(self.file_edit.text()) simplified_json = voiceflow_json.simplified_json() self.settings.setValue("simplified json", simplified_json) create_ivr = Dialplan("asterisk_docker/conf/asterisk-build/extensions.conf", simplified_json) create_ivr.create_config() class LoginWidget(QWidget): """Dialog.""" def __init__(self): """Initializer.""" super().__init__() self.init_ui() def init_ui(self): self.layout = QVBoxLayout() heading_font = QFont('Arial', 12) heading_font.setBold(True) heading = QLabel("Voiceflow Credentials:") heading.setFont(heading_font) self.layout.addWidget(QLabel()) self.layout.addWidget(heading) page_info = QLabel("Enter your Voiceflow username and password.\nYou can then use a Voiceflow project to generate an IVR") self.layout.addWidget(page_info) self.layout.addWidget(QLabel()) self.button_group = QGroupBox() self.layout.addWidget(self.button_group) self.v_box = QVBoxLayout() self.button_group.setLayout(self.v_box) self.form_layout = QFormLayout() self.email_layout = QHBoxLayout() self.email = QLineEdit() self.email_layout.addWidget(QLabel()) self.email_layout.addWidget(self.email) self.email.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.email.setToolTip("Enter your Voiceflow email") self.password_layout = QHBoxLayout() self.password = QLineEdit() self.password_layout.addWidget(QLabel()) self.password_layout.addWidget(self.password) self.password.setEchoMode(QLineEdit.Password) self.password.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.password.setToolTip("Enter your Voiceflow password") self.form_layout.addRow('', QLabel()) self.form_layout.addRow('Email:', self.email_layout) self.form_layout.addRow('Password:', self.password_layout) self.form_layout.addRow('', QLabel()) self.v_box.addLayout(self.form_layout) self.login_layout = QHBoxLayout() self.login_button = QPushButton('Login', self) self.login_button.setToolTip("Log in to Voiceflow and display projects to choose from") back_button_creator = BackButton() self.back_button = back_button_creator.create_back_button() self.login_layout.addWidget(self.back_button) self.login_layout.addWidget(self.login_button) self.v_box.addLayout(self.login_layout) self.layout.addLayout(self.v_box) self.setLayout(self.layout) def project_window(self): self.voiceflow_api = Get_Voiceflow_Information(email=self.email.text(), password=self.password.text()) self.auth_token = self.voiceflow_api.get_auth_header() if self.auth_token == "None": msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error\n\nVoiceflow Credentials were Incorrect") msg.setWindowTitle("Error") msg.exec_() return False else: return True class IvrGeneratorWidget(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.layout = QVBoxLayout() heading_font = QFont('Arial', 12) heading_font.setBold(True) heading = QLabel("Generate an IVR:") heading.setFont(heading_font) page_info1 = QLabel("Our IVR Generator allows you to either use your Voiceflow credentials \nor a downloaded Voiceflow file to generate an IVR.") page_info2 = QLabel("Voice files are automatically generated but can be added individually.") self.layout.addWidget(QLabel()) self.layout.addWidget(heading) self.layout.addWidget(page_info1) self.layout.addWidget(page_info2) self.layout.addWidget(QLabel()) self.button_group = QGroupBox() self.layout.addWidget(self.button_group) self.v_box = QVBoxLayout() self.button_group.setLayout(self.v_box) self.voiceflow_to_json_button = QPushButton('Use Voiceflow Login', self) self.voiceflow_to_json_button.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) login_icon = QIcon(os.path.join(application_path, "voiceflow_to_json/ui_assets/login_icon.png")) self.voiceflow_to_json_button.setIcon(login_icon) self.voiceflow_to_json_button.setIconSize(QSize(64, 64)) self.voiceflow_to_json_button.setToolTip("Use This To: Login to Voiceflow and choose a project to turn into an IVR") self.json_file_button = QPushButton('Use Downloaded Voiceflow File', self) self.json_file_button.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) file_icon = QIcon(os.path.join(application_path, "voiceflow_to_json/ui_assets/file_icon.png")) self.json_file_button.setIcon(file_icon) self.json_file_button.setIconSize(QSize(64, 64)) self.json_file_button.setToolTip("Use This To: Upload a Voiceflow file to turn into and IVR") self.add_voice_files_button = QPushButton("Add IVR Voice Files", self) self.add_voice_files_button.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) wav_icon = QIcon(os.path.join(application_path, "voiceflow_to_json/ui_assets/wav_icon.png")) self.add_voice_files_button.setIcon(wav_icon) self.add_voice_files_button.setIconSize(QSize(64, 64)) self.add_voice_files_button.setToolTip("Use This To: Add your own WAV voice files to the IVR") back_button_creator = BackButton() self.back_button = back_button_creator.create_back_button() back_layout = back_button_creator.create_back_layout(self.back_button) self.v_box.addWidget(self.voiceflow_to_json_button) self.v_box.addWidget(QLabel()) self.v_box.addWidget(self.json_file_button) self.v_box.addWidget(QLabel()) self.v_box.addWidget(self.add_voice_files_button) self.v_box.addWidget(QLabel()) self.v_box.addLayout(back_layout) self.setLayout(self.layout) class HomePageWidget(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.layout = QVBoxLayout() header_layout = QHBoxLayout() nhs_logo = QLabel() pixmap = QPixmap(os.path.join(application_path, "voiceflow_to_json/ui_assets/IXNforNHS.png")) pixmap = pixmap.scaled(170, 170, Qt.KeepAspectRatio) nhs_logo.setPixmap(pixmap) heading_font = QFont('Arial', 16) heading_font.setBold(True) sub_heading_font = QFont('Arial', 11) sub_heading_font.setBold(True) sub_heading = QLabel("Create an automated call triage for patients\nI(nteractive) V(oice) R(esponse)") sub_heading.setFont(sub_heading_font) heading = QLabel("GP IVR") heading.setFont(heading_font) header_layout.addWidget(nhs_logo) heading_layout = QVBoxLayout() heading_layout.addWidget(heading) heading_layout.addWidget(sub_heading) header_layout.addLayout(heading_layout) visit_website = QLabel("*For any queries on how to use the program, please refer to the user manual on our website") self.layout.addWidget(QLabel()) self.layout.addLayout(header_layout) self.layout.addWidget(QLabel()) self.layout.addWidget(visit_website) self.layout.addWidget(QLabel()) self.button_group = QGroupBox() self.layout.addWidget(self.button_group) self.v_box = QVBoxLayout() self.button_group.setLayout(self.v_box) self.generate_ivr_button = QPushButton('Generate IVR', self) self.generate_ivr_button.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) ivr_icon = QIcon(os.path.join(application_path, "voiceflow_to_json/ui_assets/ivr_logo_icon.png")) self.generate_ivr_button.setIcon(ivr_icon) self.generate_ivr_button.setIconSize(QSize(64, 64)) self.generate_ivr_button.setToolTip("Use This To: Turn a Voiceflow file or project into an IVR") self.stats_button = QPushButton('Analytics', self) self.stats_button.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) analytics_icon = QIcon(os.path.join(application_path, "voiceflow_to_json/ui_assets/analytics_icon.png")) self.stats_button.setIcon(analytics_icon) self.stats_button.setIconSize(QSize(64, 64)) self.stats_button.setToolTip("Use This To: See Analytics about your currently running IVR") self.pstn_settings_button = QPushButton('SIP Trunk Settings', self) self.pstn_settings_button.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) pstn_settings_icon = QIcon(os.path.join(application_path, "voiceflow_to_json/ui_assets/pstn_settings_icon.png")) self.pstn_settings_button.setIcon(pstn_settings_icon) self.pstn_settings_button.setIconSize(QSize(64, 64)) self.pstn_settings_button.setToolTip("Use This To: Update your PSTN provider settings for your IVR (e.g. Twilio)") self.redirect_settings_button = QPushButton('Redirect Settings', self) self.redirect_settings_button.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) redirect_settings_icon = QIcon(os.path.join(application_path, "voiceflow_to_json/ui_assets/redirect_settings_icon.png")) self.redirect_settings_button.setIcon(redirect_settings_icon) self.redirect_settings_button.setIconSize(QSize(64, 64)) self.redirect_settings_button.setToolTip("Use This To: Update the numbers that users calling the IVR are redirected to") self.v_box.addWidget(self.generate_ivr_button) self.v_box.addWidget(QLabel()) self.v_box.addWidget(self.stats_button) self.v_box.addWidget(QLabel()) self.v_box.addWidget(self.pstn_settings_button) self.v_box.addWidget(QLabel()) self.v_box.addWidget(self.redirect_settings_button) self.setLayout(self.layout) class RedirectSettingsWidget(QWidget): def __init__(self, page): super().__init__() self.page = page self.init_ui() def init_ui(self): self.layout = QVBoxLayout() self.settings = QSettings("redirect_settings", "GP_IVR_Settings") heading_font = QFont('Arial', 12) heading_font.setBold(True) rules_font = QFont('Arial', 10) rules_font.setItalic(True) self.layout.addWidget(QLabel()) heading = QLabel("Redirect Phone Numbers:") heading.setFont(heading_font) self.layout.addWidget(heading) page_info = QLabel("Here you can change the phone numbers that users are redirected\nto after reaching particular message end-points in the IVR.\nIf you don't want a user redirected, leave the value blank.") self.layout.addWidget(page_info) self.layout.addWidget(QLabel()) uk_number_rules = QLabel("* UK Numbers Only") uk_number_rules.setFont(rules_font) self.layout.addWidget(uk_number_rules) no_extension_rule = QLabel("* Don't add Extension") no_extension_rule.setFont(rules_font) self.layout.addWidget(no_extension_rule) self.voiceflow_settings = QSettings("simplified_voiceflow", "GP_IVR_Settings") self.redirect_numbers = {} self.setup_redirects_form() self.init_settings() self.button_layout = QHBoxLayout() if not self.page == "project": back_button_creator = BackButton() self.back_button = back_button_creator.create_back_button() self.button_layout.addWidget(self.back_button) else: self.button_layout.addWidget(QLabel()) self.apply_settings_button = QPushButton("Apply") self.apply_settings_button.setToolTip("Update telephone numbers that users calling the IVR are redirected to") self.button_layout.addWidget(self.apply_settings_button) self.layout.addWidget(QLabel()) self.layout.addLayout(self.button_layout) self.setLayout(self.layout) def init_settings(self): provider_number = self.settings.value("provider number") if provider_number: self.provider_number.setText(provider_number) for node in self.redirect_numbers: node_value = self.settings.value(node) if node_value: self.redirect_numbers[node].setText(node_value) def setup_redirects_form(self): voiceflow_settings = GetVoiceflowSettings(self.voiceflow_settings.value("simplified json")) redirect_texts = voiceflow_settings.get_redirect_texts() if redirect_texts == -1: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error\n\nYou have not set up an IVR") msg.setWindowTitle("Error") msg.exec_() return self.provider_number = QLineEdit() self.provider_number.setToolTip("Enter the telephone number users should call to access your IVR - you must own this number") self.button_group = QGroupBox() self.layout.addWidget(self.button_group) self.v_box = QHBoxLayout() self.button_group.setLayout(self.v_box) self.v_box.addWidget(QLabel("Provider Telephone Number:")) self.v_box.addWidget(self.provider_number, alignment=Qt.AlignRight) for node in redirect_texts: self.add_redirects(redirect_texts[node], node) def add_redirects(self, redirect_text, redirect_node): redirect_text = QLabel(redirect_text) redirect_text.setWordWrap(True) redirect_number = QLineEdit() redirect_number.setToolTip("Enter a UK telephone number without extension") self.button_group = QGroupBox() self.layout.addWidget(self.button_group) self.v_box = QHBoxLayout() self.button_group.setLayout(self.v_box) self.v_box.addWidget(redirect_text) grow_label = QLabel() self.v_box.addWidget(grow_label) grow_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.v_box.addWidget(redirect_number, alignment=Qt.AlignRight) self.redirect_numbers[redirect_node] = redirect_number def apply_settings(self): self.save_settings() phone_numbers = [] node_ids = [] if not self.provider_number.text().isnumeric(): msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error\n\nProvider Number is Not in Correct Format") msg.setWindowTitle("Error") msg.exec_() return for node in self.redirect_numbers: node_ids.append(node) if not self.redirect_numbers[node].text().isnumeric(): if not self.redirect_numbers[node].text(): continue msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error\n\nPhone Number is Not in Correct Format") msg.setWindowTitle("Error") msg.exec_() return phone_numbers.append(self.redirect_numbers[node].text()) modify_dialplan = SettingsToDialplan("asterisk_docker/conf/asterisk-build/extensions.conf", node_ids, phone_numbers, self.provider_number.text()) modify_dialplan.configure_dialplan() def save_settings(self): self.settings.clear() self.settings.setValue("provider number", self.provider_number.text()) for node in self.redirect_numbers: self.settings.setValue(node, self.redirect_numbers[node].text()) class PstnSettingsWidget(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.layout = QVBoxLayout() self.form_layout = QFormLayout() heading_font = QFont('Arial', 12) heading_font.setBold(True) heading = QLabel("SIP Trunk Settings:") heading.setFont(heading_font) self.layout.addWidget(QLabel()) self.layout.addWidget(heading) page_info = QLabel("You can change your telephone service provider SIP trunk settings here.\nThese settings must be updated from the default before running an IVR.\nMake sure that you have created a SIP trunk with your telephone provider.") self.layout.addWidget(page_info) self.layout.addWidget(QLabel()) self.button_group = QGroupBox("Mandatory Fields are Marked with *") self.layout.addWidget(self.button_group) self.v_box = QVBoxLayout() self.button_group.setLayout(self.v_box) self.form_layout.addRow("", QLabel()) self.pjsip_port = QLineEdit() self.pjsip_port.setToolTip("The port that your telephone provider will connect to the IVR with") self.provider_address = QLineEdit() self.provider_address.setToolTip("The SIP address that the IVR can contact the telephone provider through") self.provider_port = QLineEdit() self.provider_port.setToolTip("The port through which the telephone provider uses in communications") self.form_layout.addRow("Asterisk PJSIP Port (default is 5160):", self.pjsip_port) self.form_layout.addRow("*Provider Contact Address:", self.provider_address) self.form_layout.addRow("Provider Contact Port:", self.provider_port) grow_label = QLabel() self.form_layout.addRow("Provider Contact IP Addresses:", grow_label) grow_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.v_box.addLayout(self.form_layout) self.ip_form_layout = QFormLayout() self.ip_addresses = [] self.delete_button_group = QButtonGroup(self) self.delete_layouts = [] self.settings = QSettings("gp_ivr_settings", "GP_IVR_Settings") self.v_box.addLayout(self.ip_form_layout) self.init_settings() self.button_layout = QHBoxLayout() back_button_creator = BackButton() self.back_button = back_button_creator.create_back_button() self.button_layout.addWidget(self.back_button) self.add_ip_address_button = QPushButton("Add IP Address", self) self.add_ip_address_button.setToolTip("Add another contact IP address") self.button_layout.addWidget(self.add_ip_address_button) self.apply_settings_button = QPushButton("Apply") self.apply_settings_button.setToolTip("Update Sip Trunk settings for contact between your IVR and telephone provider") self.button_layout.addWidget(self.apply_settings_button) self.v_box.addWidget(QLabel()) self.v_box.addLayout(self.button_layout) self.setLayout(self.layout) def init_settings(self): self.pjsip_port.setText(self.settings.value("pjsip port")) self.provider_address.setText(self.settings.value("provider contact address")) self.provider_port.setText(self.settings.value("provider contact port")) saved_ip_addresses = self.settings.value("provider ip addresses") if saved_ip_addresses is not None: new_ip_addresses = list(saved_ip_addresses.split(",")) del new_ip_addresses[-1] for ip_address in new_ip_addresses: self.add_ip_address(value=ip_address) def add_ip_address(self, value=None): layout = QHBoxLayout() delete_ip_address_button = QPushButton("Delete", self) delete_ip_address_button.setToolTip("Remove this contact IP address") new_ip_address = QLineEdit() new_ip_address.setToolTip("IP address that the telephone provider will contact the IVR with") layout.addWidget(new_ip_address) layout.addWidget(delete_ip_address_button) if value is not None: new_ip_address.setText(value) self.ip_form_layout.addRow("IP Address " + str(len(self.ip_addresses)), layout) self.ip_addresses.append(new_ip_address) self.delete_button_group.addButton(delete_ip_address_button) def apply_settings(self): self.save_settings() ip_addresses = [] if not self.pjsip_port.text(): pjsip_port_text = "5160" else: pjsip_port_text = self.pjsip_port.text() if not self.provider_port.text(): provider_port_text = "5060" else: provider_port_text = self.provider_port.text() for ip_address in self.ip_addresses: ip_addresses.append(ip_address.text()) create_pjsip = SettingsToPjsip("asterisk_docker/conf/asterisk-build/pjsip.conf", pjsip_port_text, self.provider_address.text(), provider_port_text, ip_addresses) create_pjsip.create_config() def save_settings(self): self.settings.setValue("pjsip port", self.pjsip_port.text()) self.settings.setValue("provider contact address", self.provider_address.text()) self.settings.setValue("provider contact port", self.provider_port.text()) ip_address_list = "" for ip_address in self.ip_addresses: ip_address_list += ip_address.text() + "," if ip_address_list is not None: self.settings.setValue("provider ip addresses", ip_address_list) def delete_ip_address(self, button): ip_index = - 2 - self.delete_button_group.id(button) self.ip_form_layout.removeRow(ip_index) del self.ip_addresses[ip_index] for button in self.delete_button_group.buttons(): button_id = self.delete_button_group.id(button) if(button_id < - 2 - ip_index): self.delete_button_group.setId(button, button_id + 1) class StatsWidget(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) self.button1 = QPushButton('DAILY') self.button2 = QPushButton('WEEKLY') self.plot1() self.button1.clicked.connect(self.plot1) self.button2.clicked.connect(self.plot2) main_layout = QVBoxLayout() main_layout.addWidget(self.toolbar) main_layout.addWidget(self.canvas) sublayout = QHBoxLayout() sublayout.addWidget(self.button1) sublayout.addWidget(self.button2) main_layout.addLayout(sublayout) back_button_creator = BackButton() self.back_button = back_button_creator.create_back_button() back_layout = back_button_creator.create_back_layout(self.back_button) main_layout.addLayout(back_layout) self.setLayout(main_layout) def plot1(self): self.button1.setEnabled(False) self.button2.setEnabled(True) self.figure.clear() ax = self.figure.add_subplot() dates, outcomes = return_daily_data(10) x = np.arange(len(dates)) width = 0.2 rects1 = ax.bar(x - 3 * width / 2, outcomes[0], width, label='Answered') rects2 = ax.bar(x - width / 2, outcomes[1], width, label='No Answer') rects3 = ax.bar(x + width / 2, outcomes[2], width, label='Busy') rects4 = ax.bar(x + 3 * width / 2, outcomes[3], width, label='Failed') ax.set_ylabel('Number of Calls') ax.set_title('Calls Outcome') ax.set_xticks(x) ax.set_xticklabels(dates[:10]) ax.xaxis_date() ax.legend() self.figure.autofmt_xdate() self.figure.tight_layout() plt.grid(linestyle='--', linewidth=0.3) self.canvas.draw() def plot2(self): self.button1.setEnabled(True) self.button2.setEnabled(False) self.figure.clear() ax = self.figure.add_subplot() dates, outcomes = return_weekly_data(6) x = np.arange(len(dates)) width = 0.2 rects1 = ax.bar(x - 3 * width / 2, outcomes[0], width, label='Answered') rects2 = ax.bar(x - width / 2, outcomes[1], width, label='No Answer') rects3 = ax.bar(x + width / 2, outcomes[2], width, label='Busy') rects4 = ax.bar(x + 3 * width / 2, outcomes[3], width, label='Failed') ax.set_ylabel('Number of Calls') ax.set_title('Calls Outcome') ax.set_xticks(x) ax.set_xticklabels(dates[:10]) ax.xaxis_date() ax.legend() self.figure.autofmt_xdate() self.figure.tight_layout() plt.grid(linestyle='--', linewidth=0.3) self.canvas.draw() class AddVoiceFilesWidget(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.layout = QVBoxLayout() self.settings = QSettings("voice_file_settings", "GP_IVR_Settings") self.browse_button_group = QButtonGroup(self) heading_font = QFont('Arial', 12) heading_font.setBold(True) rules_font = QFont('Arial', 10) rules_font.setItalic(True) self.layout.addWidget(QLabel()) heading = QLabel("Add IVR Voice Files:") heading.setFont(heading_font) page_info = QLabel("You can add personal recorded voice files in place of the automatically\n generated voice files for each question in the IVR.") file_type_rule = QLabel("* WAV Files Only") file_type_rule.setFont(rules_font) self.layout.addWidget(heading) self.layout.addWidget(page_info) self.layout.addWidget(file_type_rule) self.voiceflow_settings = QSettings("simplified_voiceflow", "GP_IVR_Settings") self.voice_files = {} self.node_ids = [] self.setup_voice_files_form() self.init_settings() self.button_layout = QHBoxLayout() back_button_creator = BackButton() self.back_button = back_button_creator.create_back_button() self.button_layout.addWidget(self.back_button) self.apply_settings_button = QPushButton("Apply") self.apply_settings_button.setToolTip("Replace IVR voice files with updated files") self.button_layout.addWidget(self.apply_settings_button) self.layout.addWidget(QLabel()) self.layout.addLayout(self.button_layout) self.setLayout(self.layout) def init_settings(self): for node in self.voice_files: node_value = self.settings.value(node) if node_value: self.voice_files[node].setText(node_value) def setup_voice_files_form(self): voiceflow_settings = GetVoiceflowSettings(self.voiceflow_settings.value("simplified json")) ivr_texts = voiceflow_settings.get_ivr_texts() for node in ivr_texts: self.add_voice_file_input(ivr_texts[node], node) def add_voice_file_input(self, ivr_text, ivr_node): ivr_text = QLabel(ivr_text) ivr_text.setWordWrap(True) voice_file = WavFileEdit(self) self.button_group = QGroupBox() self.layout.addWidget(self.button_group) self.v_box = QHBoxLayout() self.button_group.setLayout(self.v_box) browse_files_button = QPushButton("Browse", self) browse_files_button.setToolTip("Browse file manager for WAV file") self.v_box.addWidget(ivr_text) grow_label = QLabel() self.v_box.addWidget(grow_label) grow_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.v_box.addWidget(voice_file) self.v_box.addWidget(browse_files_button) self.voice_files[ivr_node] = voice_file self.browse_button_group.addButton(browse_files_button) self.node_ids.append(ivr_node) def get_files(self, voice_file_edit): filepath = QFileDialog.getOpenFileName(self, 'Single File', "~", '*.wav') voice_file_edit.setText(filepath[0]) def apply_settings(self): self.save_settings() voice_file_paths = [] node_ids = [] for node in self.voice_files: voice_file_path_text = self.voice_files[node].text() voice_file_path = Path(voice_file_path_text) if not voice_file_path.is_file(): if not voice_file_path_text: continue msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error\n\nThe Path Specified is not a File") msg.setWindowTitle("Error") msg.exec_() return node_ids.append(node) voice_file_paths.append(self.voice_files[node].text()) if voice_file_paths: modify_voice_files = ModifyVoiceFiles("asterisk_docker/conf/asterisk-build/voice", node_ids, voice_file_paths) modify_voice_files.replace_asterisk_voice_files() def save_settings(self): self.settings.clear() for node in self.voice_files: if self.voice_files[node].text(): self.settings.setValue(node, self.voice_files[node].text()) def browse_files(self, button): voice_file_index = - 2 - self.browse_button_group.id(button) self.get_files(self.voice_files[self.node_ids[voice_file_index]]) class ProxyStyle(QProxyStyle): def drawControl(self, element, option, painter, widget=None): if element == QStyle.CE_PushButtonLabel: icon = QIcon(option.icon) option.icon = QIcon() super(ProxyStyle, self).drawControl(element, option, painter, widget) if element == QStyle.CE_PushButtonLabel: if not icon.isNull(): iconSpacing = 4 mode = ( QIcon.Normal if option.state & QStyle.State_Enabled else QIcon.Disabled ) if ( mode == QIcon.Normal and option.state & QStyle.State_HasFocus ): mode = QIcon.Active state = QIcon.Off if option.state & QStyle.State_On: state = QIcon.On window = widget.window().windowHandle() if widget is not None else None pixmap = icon.pixmap(window, option.iconSize, mode, state) pixmapWidth = pixmap.width() / pixmap.devicePixelRatio() pixmapHeight = pixmap.height() / pixmap.devicePixelRatio() iconRect = QRect( QPoint(), QSize(pixmapWidth, pixmapHeight) ) iconRect.moveCenter(option.rect.center()) iconRect.moveLeft(option.rect.left() + iconSpacing) iconRect = self.visualRect(option.direction, option.rect, iconRect) iconRect.translate( self.proxy().pixelMetric( QStyle.PM_ButtonShiftHorizontal, option, widget ), self.proxy().pixelMetric( QStyle.PM_ButtonShiftVertical, option, widget ), ) painter.drawPixmap(iconRect, pixmap) class ProgramUi(QMainWindow): """PyCalc's View (GUI).""" def __init__(self): """View initializer.""" super().__init__() self.initUI() def initUI(self): exitAct = QAction(QIcon('exit.png'), '&Exit', self) exitAct.setShortcut('Ctrl+Q') exitAct.setStatusTip('Exit application') exitAct.triggered.connect(qApp.quit) home_page_action = QAction("Home Page", self) home_page_action.triggered.connect(lambda: self.home_page_setup()) login_action = QAction("Generate IVR", self) login_action.triggered.connect(lambda: self.ivr_generator_setup()) pstn_settings_action = QAction("SIP Trunk Settings", self) pstn_settings_action.triggered.connect(lambda: self.pstn_settings_setup()) redirect_settings_action = QAction("Redirect Settings", self) redirect_settings_action.triggered.connect(lambda: self.redirect_settings_setup("home")) stats_action = QAction("Analytics", self) stats_action.triggered.connect(lambda: self.stats_setup()) add_voice_files_action = QAction("Add IVR Voice Files", self) add_voice_files_action.triggered.connect(lambda: self.add_voice_files_setup()) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&Menu') fileMenu.addAction(home_page_action) fileMenu.addAction(login_action) fileMenu.addAction(add_voice_files_action) fileMenu.addAction(stats_action) fileMenu.addAction(pstn_settings_action) fileMenu.addAction(redirect_settings_action) fileMenu.addAction(exitAct) self.setGeometry(200, 200, 200, 200) self.home_page_setup() def home_page_setup(self): self.resize(400, 700) self.home_page = HomePageWidget() self.setCentralWidget(self.home_page) self.setWindowTitle("Home") self.home_page_events() def ivr_generator_setup(self): self.resize(600, 600) self.ivr_generator = IvrGeneratorWidget() self.setCentralWidget(self.ivr_generator) self.setWindowTitle("IVR Generation") self.ivr_generator_events() def add_voice_files_setup(self): self.resize(800, 700) self.add_voice_files = AddVoiceFilesWidget() self.add_voice_files_scroll = QScrollArea() self.add_voice_files_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.add_voice_files_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.add_voice_files_scroll.setWidgetResizable(True) self.add_voice_files_scroll.setWidget(self.add_voice_files) self.setCentralWidget(self.add_voice_files_scroll) self.setWindowTitle("Add IVR Voice Files") self.add_voice_files_events() def stats_setup(self): self.resize(800, 600) self.stats = StatsWidget() self.setCentralWidget(self.stats) self.setWindowTitle("Analytics") self.stats_events() def pstn_settings_setup(self): self.resize(550, 450) self.pstn_settings = PstnSettingsWidget() self.setCentralWidget(self.pstn_settings) self.setWindowTitle("Sip Trunk Settings") self.pstn_settings_events() def redirect_settings_setup(self, page): self.resize(600, 500) self.redirect_settings = RedirectSettingsWidget(page) self.redirect_scroll = QScrollArea() self.redirect_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.redirect_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.redirect_scroll.setWidgetResizable(True) self.redirect_scroll.setWidget(self.redirect_settings) self.setCentralWidget(self.redirect_scroll) self.setWindowTitle("Redirect Settings") self.redirect_settings_events() def login_setup(self): self.resize(500, 150) self.login = LoginWidget() self.setCentralWidget(self.login) self.setWindowTitle("Login") self.login_events() def choose_voiceflow_file_setup(self): self.resize(500, 200) self.choose_voiceflow_file = ChooseVoiceflowFileWidget() self.setCentralWidget(self.choose_voiceflow_file) self.setWindowTitle("Choose Voiceflow File") self.choose_voiceflow_file_events() def project_setup(self): self.resize(500, 150) if(self.login.project_window()): self.project = ProjectWindow(self.login.voiceflow_api, self.login.auth_token) self.setCentralWidget(self.project) self.setWindowTitle("Project Selection") self.project_events() def choose_voiceflow_file_events(self): self.choose_voiceflow_file.browse_button.clicked.connect(lambda: self.choose_voiceflow_file.get_files()) self.choose_voiceflow_file.create_ivr_button.clicked.connect(lambda: self.choose_voiceflow_file.create_ivr()) self.choose_voiceflow_file.create_ivr_button.clicked.connect(lambda: self.choose_voiceflow_file.close()) self.choose_voiceflow_file.create_ivr_button.clicked.connect(lambda: self.resize(100, 100)) self.choose_voiceflow_file.create_ivr_button.clicked.connect(lambda: self.redirect_settings_setup("project")) self.choose_voiceflow_file.back_button.clicked.connect(lambda: self.choose_voiceflow_file.close()) self.choose_voiceflow_file.back_button.clicked.connect(lambda: self.resize(100, 100)) self.choose_voiceflow_file.back_button.clicked.connect(lambda: self.ivr_generator_setup()) def home_page_events(self): self.home_page.generate_ivr_button.clicked.connect(lambda: self.home_page.close()) self.home_page.generate_ivr_button.clicked.connect(lambda: self.resize(100, 100)) self.home_page.generate_ivr_button.clicked.connect(lambda: self.ivr_generator_setup()) self.home_page.pstn_settings_button.clicked.connect(lambda: self.home_page.close()) self.home_page.pstn_settings_button.clicked.connect(lambda: self.resize(100, 100)) self.home_page.pstn_settings_button.clicked.connect(lambda: self.pstn_settings_setup()) self.home_page.redirect_settings_button.clicked.connect(lambda: self.home_page.close()) self.home_page.redirect_settings_button.clicked.connect(lambda: self.resize(100, 100)) self.home_page.redirect_settings_button.clicked.connect(lambda: self.redirect_settings_setup("home")) self.home_page.stats_button.clicked.connect(lambda: self.home_page.close()) self.home_page.stats_button.clicked.connect(lambda: self.resize(100, 100)) self.home_page.stats_button.clicked.connect(lambda: self.stats_setup()) def ivr_generator_events(self): self.ivr_generator.voiceflow_to_json_button.clicked.connect(lambda: self.ivr_generator.close()) self.ivr_generator.voiceflow_to_json_button.clicked.connect(lambda: self.resize(100, 100)) self.ivr_generator.voiceflow_to_json_button.clicked.connect(lambda: self.login_setup()) self.ivr_generator.json_file_button.clicked.connect(lambda: self.ivr_generator.close()) self.ivr_generator.json_file_button.clicked.connect(lambda: self.resize(100, 100)) self.ivr_generator.json_file_button.clicked.connect(lambda: self.choose_voiceflow_file_setup()) self.ivr_generator.add_voice_files_button.clicked.connect(lambda: self.ivr_generator.close()) self.ivr_generator.add_voice_files_button.clicked.connect(lambda: self.resize(100, 100)) self.ivr_generator.add_voice_files_button.clicked.connect(lambda: self.add_voice_files_setup()) self.ivr_generator.back_button.clicked.connect(lambda: self.ivr_generator.close()) self.ivr_generator.back_button.clicked.connect(lambda: self.resize(100, 100)) self.ivr_generator.back_button.clicked.connect(lambda: self.home_page_setup()) def add_voice_files_events(self): self.add_voice_files.apply_settings_button.clicked.connect(lambda: self.add_voice_files.apply_settings()) self.add_voice_files.browse_button_group.buttonClicked.connect(self.add_voice_files.browse_files) self.add_voice_files.apply_settings_button.clicked.connect(lambda: self.add_voice_files.close()) self.add_voice_files.apply_settings_button.clicked.connect(lambda: self.resize(100, 100)) self.add_voice_files.apply_settings_button.clicked.connect(lambda: self.ivr_generator_setup()) self.add_voice_files.back_button.clicked.connect(lambda: self.add_voice_files.close()) self.add_voice_files.back_button.clicked.connect(lambda: self.resize(100, 100)) self.add_voice_files.back_button.clicked.connect(lambda: self.ivr_generator_setup()) def pstn_settings_events(self): self.pstn_settings.add_ip_address_button.clicked.connect(lambda: self.pstn_settings.add_ip_address()) self.pstn_settings.apply_settings_button.clicked.connect(lambda: self.pstn_settings.apply_settings()) self.pstn_settings.delete_button_group.buttonClicked.connect(self.pstn_settings.delete_ip_address) self.pstn_settings.apply_settings_button.clicked.connect(lambda: self.pstn_settings.close()) self.pstn_settings.apply_settings_button.clicked.connect(lambda: self.resize(100, 100)) self.pstn_settings.apply_settings_button.clicked.connect(lambda: self.home_page_setup()) self.pstn_settings.back_button.clicked.connect(lambda: self.pstn_settings.close()) self.pstn_settings.back_button.clicked.connect(lambda: self.resize(100, 100)) self.pstn_settings.back_button.clicked.connect(lambda: self.home_page_setup()) def redirect_settings_events(self): self.redirect_settings.apply_settings_button.clicked.connect(lambda: self.redirect_settings.apply_settings()) self.redirect_settings.apply_settings_button.clicked.connect(lambda: self.redirect_settings.close()) self.redirect_settings.apply_settings_button.clicked.connect(lambda: self.resize(100, 100)) self.redirect_settings.apply_settings_button.clicked.connect(lambda: self.home_page_setup()) if not self.redirect_settings.page == "project": self.redirect_settings.back_button.clicked.connect(lambda: self.redirect_settings.close()) self.redirect_settings.back_button.clicked.connect(lambda: self.resize(100, 100)) self.redirect_settings.back_button.clicked.connect(lambda: self.home_page_setup()) def login_events(self): self.login.login_button.clicked.connect(lambda: self.project_setup()) self.login.back_button.clicked.connect(lambda: self.login.close()) self.login.back_button.clicked.connect(lambda: self.resize(100,100)) self.login.back_button.clicked.connect(lambda: self.ivr_generator_setup()) def project_events(self): self.project.workspace_combo_box.currentTextChanged.connect(lambda: self.project.on_workspace_changed(self.project.workspace_combo_box.currentText())) self.project.projects_combo_box.currentTextChanged.connect(lambda: self.project.on_project_changed(self.project.projects_combo_box.currentText())) self.project.create_ivr_button.clicked.connect(lambda: self.project.create_ivr()) self.project.create_ivr_button.clicked.connect(lambda: self.project.close()) self.project.create_ivr_button.clicked.connect(lambda: self.resize(100, 100)) self.project.create_ivr_button.clicked.connect(lambda: self.redirect_settings_setup("project")) self.project.back_button.clicked.connect(lambda: self.project.close()) self.project.back_button.clicked.connect(lambda: self.resize(100, 100)) self.project.back_button.clicked.connect(lambda: self.login_setup()) def stats_events(self): self.stats.back_button.clicked.connect(lambda: self.stats.close()) self.stats.back_button.clicked.connect(lambda: self.resize(100, 100)) self.stats.back_button.clicked.connect(lambda: self.home_page_setup()) def main(): """Main function.""" app = QApplication(sys.argv) app.setStyle('fusion') proxy_style = ProxyStyle(app.style()) app.setStyle(proxy_style) view = ProgramUi() view.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
{"/main_application/ui_modules/home_page.py": ["/main_application/constants/image_filepath_constants.py"], "/main_application/settings_modifications/settings_to_pjsip.py": ["/main_application/connect_to_asterisk/asterisk_manager.py"], "/main_application/json_to_dialplan/json_to_dialplan.py": ["/main_application/json_to_dialplan/generate_voice_files.py", "/main_application/connect_to_asterisk/asterisk_manager.py", "/main_application/constants/asterisk_filepath_constants.py"], "/main_application/ui_modules/redirect_settings_page.py": ["/main_application/voiceflow_to_json/json_decoder.py", "/main_application/settings_modifications/settings_to_dialplan.py", "/main_application/constants/asterisk_filepath_constants.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/ui_modules/UI.py": ["/main_application/ui_modules/add_voice_files_page.py", "/main_application/ui_modules/choose_voiceflow_file_page.py", "/main_application/ui_modules/home_page.py", "/main_application/ui_modules/ivr_generator_page.py", "/main_application/ui_modules/ivr_server_status_page.py", "/main_application/ui_modules/login_page.py", "/main_application/ui_modules/project_page.py", "/main_application/ui_modules/pstn_settings_page.py", "/main_application/ui_modules/redirect_settings_page.py", "/main_application/ui_modules/statistics_page.py"], "/tests/test_main_application/unit_tests/test_voiceflow_to_json.py": ["/main_application/voiceflow_to_json/voiceflow_to_json.py", "/tests/test_main_application/unit_tests/voiceflow_constants.py"], "/tests/test_main_application/unit_tests/test_ui/test_login_page.py": ["/main_application/ui_modules/UI.py"], "/tests/test_main_application/unit_tests/test_ivr_server.py": ["/main_application/constants/docker_constants.py", "/main_application/settings_modifications/ivr_server.py"], "/main_application/ui_modules/add_voice_files_page.py": ["/main_application/voiceflow_to_json/json_decoder.py", "/main_application/settings_modifications/modify_voice_files.py", "/main_application/constants/asterisk_filepath_constants.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/ui_modules/ivr_generator_page.py": ["/main_application/constants/image_filepath_constants.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/ui_modules/statistics_page.py": ["/main_application/statistics/extract_data.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/ui_modules/pstn_settings_page.py": ["/main_application/settings_modifications/settings_to_pjsip.py", "/main_application/constants/asterisk_filepath_constants.py", "/main_application/ui_modules/shared_buttons.py"], "/tests/test_main_application/integration_tests/test_voiceflow_to_json.py": ["/main_application/voiceflow_to_json/voiceflow_to_json.py", "/tests/test_main_application/integration_tests/voiceflow_constants.py"], "/main_application/ui_modules/project_page.py": ["/main_application/voiceflow_to_json/voiceflow_to_json.py", "/main_application/json_to_dialplan/json_to_dialplan.py", "/main_application/constants/asterisk_filepath_constants.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/statistics/extract_data.py": ["/main_application/constants/asterisk_filepath_constants.py"], "/tests/test_main_application/unit_tests/test_ui/test_home_page.py": ["/main_application/ui_modules/UI.py"], "/main_application/ui_modules/login_page.py": ["/main_application/voiceflow_to_json/voiceflow_to_json.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/ui_modules/choose_voiceflow_file_page.py": ["/main_application/voiceflow_to_json/voiceflow_to_json.py", "/main_application/json_to_dialplan/json_to_dialplan.py", "/main_application/constants/asterisk_filepath_constants.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/settings_modifications/ivr_server.py": ["/main_application/constants/docker_constants.py", "/main_application/constants/test_docker_constants.py"], "/main_application/ui_modules/ivr_server_status_page.py": ["/main_application/constants/image_filepath_constants.py", "/main_application/settings_modifications/ivr_server.py", "/main_application/ui_modules/shared_buttons.py"], "/main_application/settings_modifications/settings_to_dialplan.py": ["/main_application/connect_to_asterisk/asterisk_manager.py"], "/main_application/voiceflow_to_json/voiceflow_to_json.py": ["/main_application/voiceflow_to_json/json_decoder.py"], "/main_application/ui_modules/shared_buttons.py": ["/main_application/constants/image_filepath_constants.py"]}
31,384,626
perkinsms/minecraftcalc
refs/heads/main
/armor.py
#!/usr/bin/python3 class Armor: def __init__(self, helmet=None, chestplate=None, leggings=None, boots=None): self.helmet=helmet self.chestplate=chestplate self.leggings=leggings self.boots=boots return None def total_value(self): return (self.helmet.value() + self.chestplate.value() + self.leggings.value() + self.boots.value()) def total_epf(self): return (self.helmet.epf() + self.chestplate.epf() + self.leggings.epf() + self.boots.epf()) def total_protection(self): return (100 - (self.total_value() * 4) - (self.total_epf() * 4 * 0.75))
{"/main.py": ["/armor.py", "/armorpiece.py"]}
31,384,627
perkinsms/minecraftcalc
refs/heads/main
/armorpiece.py
#!/usr/bin/python3 import yaml from math import floor with open('defense.yaml') as file: defense=yaml.load(file, Loader=yaml.FullLoader) with open('epf.yaml') as file: enchant_factor = yaml.load(file, Loader=yaml.FullLoader) class ArmorPiece: def __init__(self, shape=None, material=None, enchantment=None, ench_lev=None): self.shape = shape self.material = material self.enchantment = enchantment self.ench_lev = ench_lev return None def value(self): if self.shape==None: return 0 else: return (defense[self.shape][self.material]) def epf(self): if self.enchantment==None: return 0 else: return (enchant_factor[self.enchantment]["level"][self.ench_lev])
{"/main.py": ["/armor.py", "/armorpiece.py"]}
31,384,628
perkinsms/minecraftcalc
refs/heads/main
/main.py
#!/usr/bin/python3 from armor import Armor from armorpiece import ArmorPiece from tkinter import * from tkinter import ttk armor_materials = ["turtle", "leather", "golden", "chainmail", "iron", "diamond", "netherite"] enchantment_levels = ["Prot I", "Prot II", "Prot III", "Prot IV"] def update(): print("Helmet = " + helm_combo.get()) print("Chestplate = " + chest_combo.get()) print("Leggings = " + leggings_combo.get()) print("Boots = " + boots_combo.get()) print("Helmet Enchantment = " + helm_ench_combo.get()) print("Chestplate Enchantment = " + chest_ench_combo.get()) print("Leggings Enchantment = " + leggings_ench_combo.get()) print("Boots Enchantment = " + boots_ench_combo.get()) win = Tk() helm_label = Label(win, text="Helmet") helm_label.grid(column=0, row=0, pady = 5) chest_label = Label(win, text="Chestplate") chest_label.grid(column=1, row=0, pady = 5) leggings_label = Label(win, text="Leggings") leggings_label.grid(column=2, row=0, pady = 5) boots_label = Label(win, text="boots") boots_label.grid(column=3, row=0, pady = 5) helm_combo = ttk.Combobox(win, values = armor_materials, state="NORMAL") helm_combo.set("Helmet material") helm_combo.grid(column=0, row=1, pady = 5) chest_combo = ttk.Combobox(win, values = armor_materials, state="NORMAL") chest_combo.set("Chestplate material") chest_combo.grid(column=1, row=1, pady = 5) leggings_combo = ttk.Combobox(win, values = armor_materials, state="NORMAL") leggings_combo.set("Leggings material") leggings_combo.grid(column=2, row=1, pady = 5) boots_combo = ttk.Combobox(win, values = armor_materials, state="NORMAL") boots_combo.set("Boots material") boots_combo.grid(column=3, row=1, pady = 5) helm_ench_combo = ttk.Combobox(win, values = enchantment_levels, state="NORMAL") helm_ench_combo.set("Helmet Enchantment") helm_ench_combo.grid(column=0, row=2, pady = 5) chest_ench_combo = ttk.Combobox(win, values = enchantment_levels, state="NORMAL") chest_ench_combo.set("Chestplate Enchantment") chest_ench_combo.grid(column=1, row=2, pady = 5) leggings_ench_combo = ttk.Combobox(win, values = enchantment_levels, state="NORMAL") leggings_ench_combo.set("Leggings Enchantment") leggings_ench_combo.grid(column=2, row=2, pady = 5) boots_ench_combo = ttk.Combobox(win, values = enchantment_levels, state="NORMAL") boots_ench_combo.set("Boots Enchantment") boots_ench_combo.grid(column=3, row=2, pady = 5) but_exec = Button(win, text="Update", command=update) but_exec.grid(column=1,row=3, columnspan=2) win.mainloop()
{"/main.py": ["/armor.py", "/armorpiece.py"]}
31,400,189
tjtimer/aio_pyorient
refs/heads/master
/tests/conftest.py
import asyncio import pytest from aio_pyorient import ODBClient from aio_pyorient.pool import ODBPool from .test_settings import TEST_DB, TEST_DB_PASSWORD, TEST_USER # asyncio.set_event_loop_policy(asyncio.AbstractEventLoopPolicy()) @pytest.fixture(scope="module") def gloop(): loop = asyncio.get_event_loop() asyncio.set_event_loop(loop=loop) yield loop loop.stop() loop.close() @pytest.fixture(scope="function") async def client(loop): async with ODBClient("localhost", 2424, loop=loop) as client: yield client @pytest.fixture(scope="function") async def db_client(loop): loop = asyncio.get_event_loop() async with ODBClient("localhost", 2424, loop=loop) as client: await client.open_db(TEST_DB, TEST_USER, TEST_DB_PASSWORD) yield client @pytest.fixture(scope="function") async def test_pool(loop): async with ODBPool(TEST_USER, TEST_DB_PASSWORD, db_name=TEST_DB, loop=loop) as pool: yield pool
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,190
tjtimer/aio_pyorient
refs/heads/master
/aio_pyorient/sock.py
import asyncio import struct from aio_pyorient.handler.base import short_packer from aio_pyorient.utils import AsyncCtx class ODBSocket(AsyncCtx): def __init__(self, *, host: str="localhost", port: int=2424, **kwargs): super().__init__(**kwargs) self._host = host self._port = port self._sent = asyncio.Event(loop=self._loop) self._reader, self._writer = None, None self._in_transaction = False self._props = None self.spawn( self.connect() ) @property def host(self): return self._host @property def port(self): return self._port @property def connected(self): return self._is_ready.is_set() @property def in_transaction(self): return self._in_transaction async def connect(self): self._reader, self._writer = await asyncio.open_connection( self._host, self._port, loop=self._loop ) self._sent.set() protocol = short_packer.unpack(await self._reader.readexactly(2))[0] self._is_ready.set() return protocol async def shutdown(self): self._cancelled.set() self._is_ready.clear() if self._writer is not None: self._writer.close() self._reader.set_exception(asyncio.CancelledError()) self._host = "" self._port = 0 async def send(self, buff): await self._is_ready.wait() self._sent.clear() self._writer.write(buff) await self._writer.drain() self._sent.set() return len(buff) async def recv(self, _len_to_read): await self._sent.wait() buf = await self._reader.readexactly(_len_to_read) return buf
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,191
tjtimer/aio_pyorient
refs/heads/master
/aio_pyorient/model/prop_types.py
""" prop_types """ from typing import Any PROPERTY_ATTRIBUTES = { 'LINKEDTYPE': str, 'LINKEDCLASS': str, 'MIN': int, 'MANDATORY': bool, 'MAX': int, 'NAME': str, 'NOTNULL': bool, 'REGEX': str, 'TYPE': str, 'COLLATE': str, 'READONLY': bool, 'CUSTOM': str, 'DEFAULT': Any } class PropType: _has_attributes = False def __init__(self, **kwargs): self._name = self.__class__.__name__ if len(kwargs): for k, v in kwargs.items(): self.add_attr(k, v) self._has_attributes = True @property def attributes(self): attrs = {k: v for k,v in self.__dict__.items() if k in PROPERTY_ATTRIBUTES.keys()} return attrs if len(attrs) >= 1 else None def __repr__(self): if self.attributes is None: return self._name a_str = f"{', '.join(f'{k} {v}' for k,v in self.attributes.items())}" return f"{self._name} ({a_str})" def add_attr(self, name, value): attr = str(name).upper() assert attr in PROPERTY_ATTRIBUTES.keys(), \ f'{name} is not a valid attribute' assert isinstance(value, PROPERTY_ATTRIBUTES[attr]), \ f'{value} is not a valid value for attribute {name}' if isinstance(value, str): value = f'"{value}"' self.__setattr__(attr, value) def create_cmd(self, cls, name): assert hasattr(cls, name) return f"CREATE PROPERTY {cls._name}.{name} {self.__repr__()}" def alter_cmd(self, cls, name, attr, value): assert hasattr(cls, name) return f"ALTER PROPERTY {cls._name}.{name} {attr} {value}" class Any(PropType): pass class Binary(PropType): pass class Boolean(PropType): pass class Byte(PropType): pass class Custom(PropType): pass class Date(PropType): pass class DateTime(PropType): pass class Decimal(PropType): pass class Double(PropType): pass class Embedded(PropType): pass class EmbeddedMap(PropType): pass class EmbeddedList(PropType): pass class EmbeddedSet(PropType): pass class Float(PropType): pass class Integer(PropType): pass class Link(PropType): pass class LinkBag(PropType): pass class LinkMap(PropType): pass class LinkList(PropType): pass class LinkSet(PropType): pass class Long(PropType): pass class Short(PropType): pass class String(PropType): pass class Transient(PropType): pass def props(cls): return ((k, v) for k, v in cls.__dict__.items() if isinstance(v, PropType)) def props_cmd(cls, alter_or_create: str='alter'): start = f"{alter_or_create.upper()} PROPERTY" for name, prop_type in props(cls): yield f"{start} {cls.__name__}.{name} {prop_type}"
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,192
tjtimer/aio_pyorient
refs/heads/master
/aio_pyorient/__init__.py
from .client import ODBClient __all__ = ('ODBClient',)
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,193
tjtimer/aio_pyorient
refs/heads/master
/tests/test_pool/test_pool.py
""" test_pool """ from random import randint from aio_pyorient.pool import ODBPool from tests.test_settings import TEST_DB, TEST_PASSWORD, TEST_USER async def test_pool(loop): cl_count = randint(1, 125) print(f'test will acquire {cl_count} clients') async with ODBPool(TEST_USER, TEST_PASSWORD, db_name=TEST_DB, loop=loop) as pool: assert pool.min is 5 assert pool.max == 30000 assert pool.available_clients is pool.min assert pool.is_ready all_clients = [await pool.acquire() for _ in range(cl_count)] assert all([cl.session_id >= 0 for cl in all_clients]) assert all([cl._auth_token not in (b'', '', None) for cl in all_clients]) assert all([cl._sock.connected is True for cl in all_clients]) assert len(set(all_clients)) == cl_count assert pool.done assert pool.available_clients is 0
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,194
tjtimer/aio_pyorient
refs/heads/master
/aio_pyorient/client.py
import asyncio from aio_pyorient.handler import db, server, command from aio_pyorient.odb_types import ODBClusters from aio_pyorient.sock import ODBSocket from aio_pyorient.utils import AsyncCtx try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass class ODBClient(AsyncCtx): """ ODBClient Use this to talk to your OrientDB server. """ def __init__(self, host: str = 'localhost', port: int = 2424, **kwargs): super().__init__(**kwargs) self._sock = ODBSocket(host=host, port=port, loop=self._loop) self._id = kwargs.pop('client_id', '') self._session_id = kwargs.pop("session_id", -1) self._auth_token = kwargs.pop("auth_token", b'') self._db_name = kwargs.pop("db_name", '') self._clusters = kwargs.pop("clusters", ODBClusters()) self._cluster_conf = kwargs.pop("cluster_conf", b'') self._server_version = kwargs.pop("server_version", '') self._protocol = None self._serialization_type = "ORecordDocument2csv" self._is_ready.set() @property def is_ready(self): return self._sock.connected and self._is_ready.is_set() @property def protocol(self): return self._protocol @property def session_id(self): return self._session_id @property def auth_token(self): return self._auth_token @property def active_db(self): return self._db_name @property def clusters(self): return self._clusters @property def cluster_conf(self): return self._cluster_conf @property def server_version(self): return self._server_version async def _shutdown(self): await self._sock.shutdown() async def connect(self, user: str, password: str, **kwargs): handler = await server.ServerConnect(self, user, password, **kwargs).send() return await handler.read() async def create_db(self, db_name: str, storage_type: str, **kwargs): handler = await db.CreateDb(self, db_name, storage_type, **kwargs).send() return await handler.read() async def drop_db(self, db_name: str, storage_type: str, **kwargs): handler = await db.DropDb(self, db_name, storage_type, **kwargs).send() return await handler.read() async def open_db(self, db_name: str, user: str, password: str, **kwargs): handler = await db.OpenDb(self, db_name, user, password, **kwargs).send() return await handler.read() async def reload_db(self, **kwargs): handler = await db.ReloadDb(self, **kwargs).send() return await handler.read() async def close_db(self, **kwargs): handler = await db.CloseDb(self, **kwargs).send() return await handler.read() async def db_exist(self, db_name: str, storage_type: str, **kwargs): handler = await db.DbExist(self, db_name, storage_type, **kwargs).send() return await handler.read() async def db_size(self, **kwargs): handler = await db.DbSize(self, **kwargs).send() return await handler.read() async def db_record_count(self, **kwargs): handler = await db.DbRecordCount(self, **kwargs).send() return await handler.read() async def execute(self, query: str, **kwargs): handler = await command.Query(self, query, **kwargs).send() return await handler.read()
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,195
tjtimer/aio_pyorient
refs/heads/master
/aio_pyorient/exceptions.py
""" exceptions """ from collections.__init__ import namedtuple ODBRequestErrorMessage = namedtuple("ODBException", "class_name, message")
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,196
tjtimer/aio_pyorient
refs/heads/master
/tests/test_handler/test_command.py
""" test_command """ import random import string import time from hypothesis import given, strategies as st, settings from aio_pyorient.handler.base import int_packer from aio_pyorient.handler.command import Query from aio_pyorient.odb_types import ODBRecord async def test_select_command(db_client): handler = Query( db_client, f"""select from #0:1""" ) await handler.send() response = await handler.read() print("response:") for item in response: print(item) assert handler.done async def test_create_command(db_client): name = st.text(alphabet=[*string.ascii_lowercase, *string.ascii_uppercase], min_size=3, max_size=25).example() age = st.integers(min_value=2, max_value=120).example() print(name, age) handler = Query( db_client, f"create vertex Person SET name='{name}', age={age}, email='{name}@mail.ex'" ) await handler.send() response = await handler.read() print("response:") print(response) for item in response: print(item) assert handler.done # db_client.spawn(test_create_command(name, age)) # time.sleep(1) async def test_update_command(db_client): age = random.randint(15, 100) handler = Query( db_client, f"""UPDATE #22:0 set age={age} RETURN AFTER @this""" ) await handler.send() response = await handler.read() print("response:") for item in response: assert isinstance(item, ODBRecord) assert item.id is not None assert handler.done
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,197
tjtimer/aio_pyorient
refs/heads/master
/setup.py
from setuptools import setup setup( name='aio_pyorient', version='0.0.1', url='https://github.com/tjtimer/aio_pyorient', author='Tim "tjtimer" Jedro', author_email='tjtimer@gmail.com', description='async OrientDB client library for python', long_description=open('README.rst').read(), license='LICENSE', packages = [ 'aio_pyorient', ], install_requires=[ 'arrow', 'pytest', 'pytest-aiohttp' ] )
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,198
tjtimer/aio_pyorient
refs/heads/master
/aio_pyorient/odb_types.py
from collections import namedtuple from aio_pyorient.serializer import serialize, Boolean, Integer, List, String, Float, Type, IntegerList, StringList ODBRecord = namedtuple("ODBRecord", "type, id, version, data") ODBCluster = namedtuple('ODBCluster', 'name, id') ODBRequestErrorMessage = namedtuple("ODBException", "class_name, message") class ODBClusters(list): def get(self, prop: int or str)->str or int: is_id = isinstance(prop, int) attr_type = 'id' if is_id else 'name' try: clusters = [cl for cl in self if prop in cl] except IndexError: raise ValueError( f"cluster with {attr_type} {prop} does not exist" ) else: if is_id: return [cluster.name for cluster in clusters] return [cluster.id for cluster in clusters] SCHEMA_SPECS = { 'abstract': Boolean, 'clusterIds': IntegerList, 'clusterSelection': String, 'customFields': String, 'defaultClusterId': Integer, 'description': String, 'name': String, 'overSize': Float, 'properties': String, 'shortName': String, 'strictMode': Boolean, 'superClass': String, 'superClasses': StringList, 'type': Type, 'notNull': Boolean, 'mandatory': Boolean } PROPS_SPECS = { 'collate': String, 'customFields': List, 'defaultValue': String, 'description': String, 'globalId': Integer, 'mandatory': Boolean, 'max': Integer, 'min': Integer, 'name': String, 'notNull': Boolean, 'readonly': Boolean, 'type': Type } class ODBSchema: def __init__(self, records): self._classes = {} for record in records: d_string = record.data.decode() props = [] props_start = d_string.find('<(') if props_start >= 0: props_end = d_string.find(')>') p_string = d_string[props_start + 1:props_end] props = [ serialize(_p, PROPS_SPECS) for _p in p_string.split('),(') ] d_string = d_string[0:props_start] + d_string[props_end+1:] data = serialize(d_string, SCHEMA_SPECS) data['properties'] = {prop['name']: prop for prop in props} self._classes[data['name']] = data def __str__(self): return f'<ODBSchema {sorted(list(self._classes.keys()))}>' @property def classes(self): return self._classes
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,199
tjtimer/aio_pyorient
refs/heads/master
/tests/test_handler/test_db.py
from pprint import pprint from aio_pyorient.handler import db from tests.test_settings import TEST_DB, TEST_DB_PASSWORD, TEST_USER signals_received = 0 async def test_db_open(client): async def increment_i(payload): global signals_received assert isinstance(payload.sender, db.OpenDb) if signals_received is 0: assert payload.extra == '_ows_' elif signals_received is 3: assert payload.extra == '_odr_' else: assert payload.extra is None signals_received += 1 return signals_received handler = db.OpenDb(client, TEST_DB, TEST_USER, TEST_DB_PASSWORD, ows_extra_payload='_ows_', odr_extra_payload='_odr_' ) handler.on_will_send(increment_i) handler.on_did_send(increment_i) handler.on_will_read(increment_i) handler.on_did_read(increment_i) assert handler._sent.is_set() is False assert handler.done is False assert signals_received is 0 await handler.send() assert handler._sent.is_set() is True assert handler.done is False assert signals_received is 2 # will_send, did_send await handler.read() assert handler.done is True assert signals_received is 4 # will_send, did_send, will_read, did_read assert client.session_id is not -1 assert client.auth_token not in (b'', None) assert client.active_db == TEST_DB assert len(client.clusters) > 0 for cluster in client.clusters: assert cluster.id >= 0 assert isinstance(cluster.name, str) assert cluster.name != "" assert 0 in client.clusters.get('internal') assert 'internal' in client.clusters.get(0) assert client.server_version not in (None, '') pprint(vars(client))
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,200
tjtimer/aio_pyorient
refs/heads/master
/aio_pyorient/model/base.py
""" base """ from aio_pyorient.model.prop_types import props InitCommands = [] vertex_registry = [] edge_registry = [] class ODBVertex: def __init_subclass__(cls): cls._name = cls.__name__ vertex_registry.append(cls) def __init__(self, **kwargs): for k, v in kwargs.items(): self.__setattr__(k, v) def __setattr__(self, name, value): print("setting attribute: ", name, value) self.__dict__[name] = value @property def props(self): return dict(props(self.__class__)) class ODBEdge: def __init_subclass__(cls): edge_registry.append(cls) cls.label = cls.__name__.lower()
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,201
tjtimer/aio_pyorient
refs/heads/master
/tests/test_graph/test_graph.py
""" test_graph """ from pprint import pprint from aio_pyorient.graph import ODBGraph from aio_pyorient.odb_types import ODBSchema from tests.test_settings import TEST_USER, TEST_PASSWORD, TEST_DB async def test_graph(): async with ODBGraph(TEST_USER, TEST_PASSWORD, TEST_DB) as graph: assert isinstance(graph._schema, ODBSchema) assert 'V' in graph._schema.classes.keys() assert 'E' in graph._schema.classes.keys() pprint(graph._schema.classes)
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,202
tjtimer/aio_pyorient
refs/heads/master
/tests/test_handler/test_server.py
""" test_server """ from aio_pyorient.handler import server from tests.test_settings import TEST_PASSWORD, TEST_USER async def test_connect(client): handler = server.ServerConnect(client, TEST_USER, TEST_PASSWORD) await handler.send() await handler.read() assert client._session_id > 0 assert client._auth_token not in (b'', None) assert handler.done
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,400,203
tjtimer/aio_pyorient
refs/heads/master
/aio_pyorient/serializer.py
""" serializer """ import re TYPE_MAP = { '1': 'Boolean', '2': 'Byte', '3': 'Short', '4': 'Integer', '5': 'Long', '6': 'Bytes', '7': 'String', '8': 'Record', '9': 'Strings', '10': 'Char', '11': 'Link' } float_reg = re.compile(r'-?[0-9]+\.?[0-9]*') int_reg = re.compile(r'-?[0-9]+') str_reg = re.compile(r'[a-zA-Z]+') Key = lambda v: str_reg.search(v).group(0) String = lambda v: v[1:-1] if len(v) > 1 else v Integer = lambda v: int(int_reg.search(v).group(0)) if len(v) else None Float = lambda v: float(v[:-1]) Boolean = lambda v: True if v.upper() == 'TRUE' else False List = lambda v: v[1:-1].split(', ') if len(v) > 1 else [] FloatList = lambda v: list(float(x) for x in float_reg.findall(v)) IntegerList = lambda v: list(int(x) for x in int_reg.findall(v)) StringList = lambda v: list(x for x in str_reg.findall(v)) Type = lambda v: TYPE_MAP[v] key_reg = re.compile(r',?@?[a-zA-Z0-9_\-]+:') def serialize(data: str, specs: dict)->dict: data.replace('"', '') matches = list(key_reg.finditer(data)) key_count = len(matches) keys = [] values = [] if key_count: for i in range(key_count - 1): key = Key(matches[i].group(0)) value = data[matches[i].end():matches[i + 1].start()] keys.append(key) try: values.append(specs[key](value)) except KeyError: values.append(value) key = Key(matches[-1].group(0)[1:-1]) keys.append(key) value = data[matches[-1].end() + 1:] try: values.append(specs[key](value)) except KeyError: values.append(value) return dict(zip(keys, values))
{"/aio_pyorient/client.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/schema/prop_types.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/sock.py", "/aio_pyorient/utils.py"], "/tests/test_handler/test_command.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py"], "/aio_pyorient/message/base.py": ["/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/schema/base.py": ["/aio_pyorient/schema/prop_types.py", "/aio_pyorient/utils.py"], "/aio_pyorient/message/server.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/serializer.py": ["/aio_pyorient/schema/prop_types.py"], "/tests/test_client/test_schema.py": ["/aio_pyorient/odb_types.py"], "/tests/conftest.py": ["/aio_pyorient/client.py", "/aio_pyorient/__init__.py", "/aio_pyorient/pool.py"], "/tests/test_handler/test_db.py": ["/tests/conftest.py"], "/tests/test_graph/test_graph.py": ["/aio_pyorient/graph.py", "/aio_pyorient/odb_types.py", "/tests/conftest.py"], "/tests/test_pool/test_pool.py": ["/aio_pyorient/pool.py", "/tests/conftest.py"], "/aio_pyorient/message/db.py": ["/aio_pyorient/odb_types.py", "/aio_pyorient/message/base.py", "/aio_pyorient/message/encoder.py"], "/aio_pyorient/message/command.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/message/encoder.py"], "/tests/test_handler/test_server.py": ["/tests/conftest.py"], "/aio_pyorient/sock.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/utils.py"], "/aio_pyorient/odb_types.py": ["/aio_pyorient/serializer.py"], "/aio_pyorient/message/encoder.py": ["/aio_pyorient/message/base.py", "/aio_pyorient/message/constants.py"], "/aio_pyorient/graph.py": ["/aio_pyorient/message/command.py", "/aio_pyorient/odb_types.py", "/aio_pyorient/pool.py", "/aio_pyorient/utils.py"], "/aio_pyorient/pool.py": ["/aio_pyorient/client.py", "/aio_pyorient/utils.py"], "/tests/test_sock.py": ["/aio_pyorient/sock.py"], "/aio_pyorient/__init__.py": ["/aio_pyorient/client.py"], "/aio_pyorient/model/base.py": ["/aio_pyorient/model/prop_types.py"]}
31,470,597
WerWolfEee/simple-notes
refs/heads/master
/sql_app/services.py
from fastapi.security import OAuth2PasswordBearer from sqlalchemy.orm import Session import sql_app.database as _database import sql_app.crud as _crud import sql_app.models as _models import sql_app.schemas as _schemas import jwt oauth2schema = OAuth2PasswordBearer(tokenUrl="/token") JWT_SECRET = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" def get_db(): db = _database.SessionLocal() try: yield db finally: db.close() def authenticate_user(email: str, password: str, db: Session): user = _crud.get_user_by_email(db=db, email=email) if not user: return False if not user.verify_password(password): return False return user def create_token(user: _models.User): user_obj = _schemas.User.from_orm(user) token = jwt.encode(user_obj.dict(), JWT_SECRET) return dict(access_token=token, token_type="bearer")
{"/sql_app/main.py": ["/sql_app/database.py", "/sql_app/crud.py", "/sql_app/schemas.py", "/sql_app/services.py"], "/sql_app/services.py": ["/sql_app/database.py", "/sql_app/crud.py", "/sql_app/models.py", "/sql_app/schemas.py"], "/sql_app/models.py": ["/sql_app/database.py"], "/sql_app/crud.py": ["/sql_app/models.py", "/sql_app/schemas.py", "/sql_app/services.py"]}
31,470,598
WerWolfEee/simple-notes
refs/heads/master
/sql_app/database.py
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # for using a SQLite database uncomment the line: # SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" # for using a PostgreSQL database uncomment the line: SQLALCHEMY_DATABASE_URL = "postgresql://postgres:pOSTgRE@localhost:5432/postgre_sql_app" # for using a SQLite database uncomment the line: # engine = create_engine( # SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} # ) # for using a PostgreSQL database uncomment the line: engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base()
{"/sql_app/main.py": ["/sql_app/database.py", "/sql_app/crud.py", "/sql_app/schemas.py", "/sql_app/services.py"], "/sql_app/services.py": ["/sql_app/database.py", "/sql_app/crud.py", "/sql_app/models.py", "/sql_app/schemas.py"], "/sql_app/models.py": ["/sql_app/database.py"], "/sql_app/crud.py": ["/sql_app/models.py", "/sql_app/schemas.py", "/sql_app/services.py"]}
31,470,599
WerWolfEee/simple-notes
refs/heads/master
/sql_app/models.py
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from passlib.hash import bcrypt import sql_app.database as _database class User(_database.Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) notes = relationship("Note", back_populates="owner") def verify_password(self, password: str): return bcrypt.verify(password, self.hashed_password) class Note(_database.Base): __tablename__ = "notes" id = Column(Integer, primary_key=True, index=True) title = Column(String, index=True) description = Column(String, index=True) completion = Column(Boolean, default=0) owner_id = Column(Integer, ForeignKey("users.id")) owner = relationship("User", back_populates="notes")
{"/sql_app/main.py": ["/sql_app/database.py", "/sql_app/crud.py", "/sql_app/schemas.py", "/sql_app/services.py"], "/sql_app/services.py": ["/sql_app/database.py", "/sql_app/crud.py", "/sql_app/models.py", "/sql_app/schemas.py"], "/sql_app/models.py": ["/sql_app/database.py"], "/sql_app/crud.py": ["/sql_app/models.py", "/sql_app/schemas.py", "/sql_app/services.py"]}